枚举专用模板

The*_* do 5 c++ templates

谁能告诉我为什么这不起作用?

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;
}
Run Code Online (Sandbox Code Playgroud)

Cha*_*via 9

您将参数化类型和参数化的概念混为一谈.模板参数可以是类型或常量.例如:

template <typename T>
struct Foo;
Run Code Online (Sandbox Code Playgroud)

与..

template <int N>
struct Foo;
Run Code Online (Sandbox Code Playgroud)

看起来你想根据枚举常量而不是类型来专门化你的模板.意思是,你需要说:

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;
}
Run Code Online (Sandbox Code Playgroud)

此外,您不能使用namespace运算符引用枚举.如果要封装枚举,则需要将它们包装在命名空间中:

namespace CompCriteria
{
   enum type {ByKey,ByValue,ByeKeyAndValue};
}
Run Code Online (Sandbox Code Playgroud)


Kir*_*sky 2

您已经专门X针对一种类型,但您尝试将其与 integer 一起使用CompCriteria::ByeKeyAndValue

您可以为enum CompCriteria基础类型专门化模板类 -int在本例中,如下所示:

enum CompCriteria{ByKey,ByValue,ByeKeyAndValue};

template<int>
struct X;

template<>
struct X<ByeKeyAndValue>
{
};

int main()
{
    X<ByeKeyAndValue> x;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)