Alt*_*tan 20 c++ enums templates template-specialization
struct Bar {
enum { Special = 4 };
};
template<class T, int K> struct Foo {};
template<class T> struct Foo<T,T::Special> {};
Run Code Online (Sandbox Code Playgroud)
用法:
Foo<Bar> aa;
Run Code Online (Sandbox Code Playgroud)
无法使用gcc编译4.1.2它抱怨使用T::SpecialFoo的部分特性.如果Special是一个类,解决方案将是前面的类型名称.枚举(或整数)是否有相当于它的东西?
Naw*_*waz 16
由于Prasoon 解释了C++不允许这样做,所以另一种解决方案是使用EnumToType类模板,
struct Bar {
enum { Special = 4 };
};
template<int e>
struct EnumToType
{
static const int value = e;
};
template<class T, class K> //note I changed from "int K" to "class K"
struct Foo
{};
template<class T>
struct Foo<T, EnumToType<(int)T::Special> >
{
static const int enumValue = T::Special;
};
Run Code Online (Sandbox Code Playgroud)
ideone上的示例代码:http://www.ideone.com/JPvZy
或者,您可以像这样专门化(如果它解决了您的问题),
template<class T> struct Foo<T,Bar::Special> {};
//usage
Foo<Bar, Bar::Special> f;
Run Code Online (Sandbox Code Playgroud)
非类型模板参数的类型不能依赖于部分特化的模板参数.
ISO C++ 03 14.5.4/9说
除非参数表达式是简单标识符,否则部分专用的非类型参数表达式不应涉及部分特化的模板参数.
template <int I, int J> struct A {};
template <int I> struct A<I+5, I*2> {}; //error
template <int I, int J> struct B {};
template <int I> struct B<I, I> {}; //OK
Run Code Online (Sandbox Code Playgroud)
所以这样的事情是非法的,template<class T> struct Foo<T,T::Special> {};因为T::Special依赖T
用法也是非法的.您提供了一个模板参数,但您需要提供两个参数.