AdyAdy
AdyAdy

Reputation: 1028

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

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.)

Upvotes: 8

Views: 5543

Answers (2)

badfd
badfd

Reputation: 63

using MySomeClass = SomeClass<int>;

MySomeClass::SomeEnum foo = MySomeClass::SomeEnum::SOME_FLAG;

Upvotes: 0

skypjack
skypjack

Reputation: 50540

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;

Upvotes: 10

Related Questions