Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Use enum from template class without template parameter

Tags:

c++

templates

template<typename T> class SomeClass{

public:
    enum SomeEnum{ SOME_FLAG};

};

SomeClass::SomeEnum some_enum =      SomeClass::SomeEnum::SOME_FLAG;       //NO
SomeClass<int>::SomeEnum some_enum = SomeClass::SomeEnum::SOME_FLAG;       //NO
SomeClass<int>::SomeEnum some_enum = SomeClass<int>::SomeEnum::SOME_FLAG;  //YES

This won't compile because

class SomeClass used without template parameters

Is there no way / workaround to use it without template parameter, kinda make that enum global for that class, so it doesn't depend on the parameter.

It's not that I can't type them but they can be long and complicated, the code will be harder to read and I can't use something like auto here. (I'm new to templates so sorry if this question is lame.)

like image 545
AdyAdy Avatar asked Aug 07 '17 06:08

AdyAdy


1 Answers

If you want to enclose your enum in a class definition for reasons (I cannot say what's the real problem), you can still introduce one more class that isn't a class template and contains the enum, then inherit from that with your class template. That's all.
As an example:

struct SomeBase {
    enum SomeEnum { SOME_FLAG };
};

template<typename>
struct SomeClass: SomeBase {
    // ...
};

Use this:

SomeBase::SomeEnum::SOME_FLAG;

Instead of this:

SomeClass::SomeEnum::SOME_FLAG;

Whenever you want to access the enum directly.
Something like the following remains valid anyway:

SomeClass<void>::SomeEnum foo = SomeClass<void>::SomeEnum::SOME_FLAG;
like image 75
skypjack Avatar answered Nov 02 '22 23:11

skypjack