Enum as a template

This is what I want to do:

enum MyEnum { ONE = 1, TWO, THREE }; template<class T> void func() { cout << T::TWO << endl; } int main() { func<MyEnum>(); }; 

This works, but I get a warning: "warning C4482: non-standard extension is used: enum" MyEnum "is used in a qualified name

How can I do this without warning

+4
source share
3 answers

Here Enum is a bit more complicated. Type ONE and TWO will be in the external namespace. Therefore, adding a type to a name leads to a warning. You can simply delete the qualifier

 template<class T> void func() { cout << TWO << endl; } 

Since TWO is known in the external namespace. You can also just move your enum to some kind of closing structure.

 struct EnumContainer { enum MyEnum { ONE = 1, TWO, THREE }; }; template<class T> void func() { std::cout << T::TWO << std::endl; } int main() { func<EnumContainer>(); }; 

Now the compiler should be fine.

+5
source

Although it would be nice to use an enumeration as a template parameter and recognize each individual enumeration separately, as you wrote it, this will not happen. Instead, I can suggest you declare the following:

 template<MyEnum T> void func(){ std::cout << T << std::endl; } 

The great thing about C ++ is that the way you structure your templates gives you the Turning complete system. Therefore, you do not need a separate call like this, since you announced that you received each individual enumeration value. You can create a separate function for each value when you need it, and only when you need it.

Now, going to another problem of your question, as @delnan commented, you cannot have two different Enums with the same name. However, you can have a class with a member variable called TWO such that:

 struct Foo{ int TWO; }; struct Bar{ int TWO; }; template<typename T> void func(){ std::cout << T::TWO << std::endl; } 

Hope this helps.

+1
source

Enums (pre C ++ 0x) are considered as integral types.

In fact, the designation MyEnum :: TWO is garbage: there is no class or namespace MyEnum. The names ONE, TWO, and THREE are listed in the namespace where the enumeration is defined [in this case, the global namespace].

You should receive an error message TWO is not a member of MyEnum .

One way to emulate behavior is to put it in a structure or class, like others.

+1
source

Source: https://habr.com/ru/post/1339205/


All Articles