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.
Enumerations make for clearer and more readable code, particularly when meaningful names are used. The benefits of using enumerations include: Reduces errors caused by transposing or mistyping numbers. Makes it easy to change values in the future.
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain.
In C++ programming, enum or enumeration is a data type consisting of named values like elements, members, etc., that represent integral constants. It provides a way to define and group integral constants. It also makes the code easy to maintain and less complex.
There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With