6

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:

  • Shall be an integer constant large enough to fit all the values of the enum
  • Each enumerated type shall be compatible with 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.

T.C.
  • 133,968
  • 17
  • 288
  • 421
PaperBirdMaster
  • 12,806
  • 9
  • 48
  • 94
  • There are only class and function templates in C++11. (C++14 is going to change that). A scoped enumeration is *not* a class, despite being declared with the `class` keyword. – n. m. could be an AI Feb 20 '14 at 17:17
  • @n.m. I know about the template variables of C++14, and I also know that the strong enums aren't classes. But the fact is that I don't know why the strong enums cannot template their underlying type, what logic (or illogic) reason is behind that explicit prohibition. – PaperBirdMaster Feb 21 '14 at 07:56
  • There's no good justification. The standsrd says so, that's all. – n. m. could be an AI Feb 21 '14 at 08:13

2 Answers2

3

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.

Loreto
  • 674
  • 6
  • 20
1

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/

Gabriel
  • 3,564
  • 1
  • 27
  • 49