struct Bar {
enum { Special = 4 };
};
template<class T, int K> struct Foo {};
template<class T> struct Foo<T,T::Special> {};
用法:
Foo<Bar> aa;
无法使用 gcc 4.1.2 编译它抱怨使用T::Special
Foo 的部分特化。如果Special
是一个类,解决方案将是它前面的类型名。枚举(或整数)是否有与之等效的东西?
struct Bar {
enum { Special = 4 };
};
template<class T, int K> struct Foo {};
template<class T> struct Foo<T,T::Special> {};
用法:
Foo<Bar> aa;
无法使用 gcc 4.1.2 编译它抱怨使用T::Special
Foo 的部分特化。如果Special
是一个类,解决方案将是它前面的类型名。枚举(或整数)是否有与之等效的东西?
由于 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;
};
ideone 的示例代码:http ://www.ideone.com/JPvZy
或者,您可以像这样简单地专业化(如果它解决了您的问题),
template<class T> struct Foo<T,Bar::Special> {};
//usage
Foo<Bar, Bar::Special> f;
非类型模板实参的类型不能依赖于偏特化的模板形参。
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
所以这样的事情是非法的template<class T> struct Foo<T,T::Special> {};
,因为T::Special
取决于T
使用也是非法的。您提供了一个模板参数,但您需要提供两个。