Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specializing template for enum

Tags:

c++

templates

Could anyone tell me why this doesn't work?

enum CompCriteria{ByKey,ByValue,ByeKeyAndValue};

template<class T>
struct X;

template<>
struct X<CompCriteria>
{
};

int _tmain(int argc, _TCHAR* argv[])
{
    X<CompCriteria::ByeKeyAndValue> x;
    return 0;
}
like image 714
There is nothing we can do Avatar asked Nov 21 '10 15:11

There is nothing we can do


People also ask

What is function template specialization?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

Why is enum size 4?

The size is four bytes because the enum is stored as an int . With only 12 values, you really only need 4 bits, but 32 bit machines process 32 bit quantities more efficiently than smaller quantities.

What is enum in C++ with example?

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.

What is the size of enum data type?

On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less. The GCC C compiler will allocate enough memory for an enum to hold any of the values that you have declared. So, if your code only uses values below 256, your enum should be 8 bits wide.


1 Answers

You're conflating the idea of parameterized types and parameterized values. A template parameter can be a type, or a constant. For example:

template <typename T>
struct Foo;

versus..

template <int N>
struct Foo;

It looks like you want to specialize your template based on an enum constant, rather than a type. Meaning, you need to say:

enum CompCriteria{ByKey,ByValue,ByeKeyAndValue};

template<CompCriteria>
struct X;

// Specialization for ByKeyAndValue
//
template<>
struct X<ByeKeyAndValue>
{
};

int main()
{
    X<ByeKeyAndValue> x; // instantiate specialization 
    return 0;
}

Also, you can't refer to enums using the namespace operator. If you want to encapsulate your enums, you need to wrap them in a namespace:

namespace CompCriteria
{
   enum type {ByKey,ByValue,ByeKeyAndValue};
}
like image 121
Charles Salvia Avatar answered Sep 24 '22 12:09

Charles Salvia