Reputation: 13320
enumeration cannot be a template
is the error given when I try to compile with BCC64 (based on Clang) the following code:
template <typename T> enum class fooEnum : T
{
a,b,c,d,e
};
At first, I was thinking that this explicit prohibition was due to the enum
underlying type limitations, if the enum underlying type could be templated, then it could lead to ill-formed enums, but when we try this:
template <typename A> struct fooClass
{
enum class fooEnum : A
{
a,b,c,d,e
};
};
It compiles without problem as long as the A
type follows the same limitations as the enum underlying types, you know, the expression that defines the value of an enumeration:
char
or a signed
/unsigned
integer type.If we do not not follow this rules, (with an in-class or a global enum) another specific error shows up, as expected:
enum class fooEnum : fooClass
{
a,b,c,d,e
};
non-integral type 'fooClass' is an invalid underlying type
So, that's why I'm wondering why is explicitly forbidden to create a template enum even when there is already a control over the underlying type. Where on the standard is mentioned this prohibition?
Thanks for your attention.
Upvotes: 6
Views: 1813
Reputation: 694
By definition [C++ standard 14.1], or by being outside of the definition,
A template defines a family of classes or functions or an alias for a family of types.
An enum is neither of these, so it cannot be a template.
Upvotes: 3
Reputation: 3594
You can sort the problem out by declaring the enum inside a class (containing only that).
Here is the code
#include <iostream>
using namespace std;
template <typename T>
struct myEnum
{
enum Values
{
a=0, b=1,c=2
};
};
int main() {
myEnum<int> abc;
cout<<abc.Values::a<< abc.Values::b<<abc.Values::c;
// your code goes here
return 0;
}
Output: 012
Tested with http://ideone.com/
Upvotes: 1