Virtual static function that differs with each derived class?

What I am trying to do is have a variable that can be accessed statically (i.e. Error::code) but each derived class can set it to a different value.

For example I can have a DownloadError class in which DownloadError::code is set to 1 and FileError::code could be something else. Is this possible or would I have to implement a static virtual function (is this possible?) that returns a constant number?

I'm thinking something like this:
1
2
3
4
5
6
7
8
9
10
class Error {
public:
    // other stuff here
    static virtual int getCode() = 0;
};

class DownloadError : public Error {
public:
    static int getCode() { return 1; }
};


Any help or guidance is greatly appreciated.

EDIT: Members cannot be declared both virtual and static, oh well. Any alternatives still welcome!
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct error
{
    virtual ~error() = default ;
    virtual int code() const = 0 ;
};

template < typename DERIVED > struct error_helper : error // CRTP
{
    virtual int code() const override { return DERIVED::error_code() ; }
};

struct download_error : error_helper<download_error>
{
    static int error_code() { return 1 ; }
};

struct upload_error : error_helper<upload_error>
{
    static int error_code() { return 6 ; }
};

http://coliru.stacked-crooked.com/a/05f99b27cbd14b2c
Thank you very much JLBorges
Topic archived. No new replies allowed.