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
是一个类,则解决方案将是它前面的类型名。枚举(或整数)是否有与之等效的东西?
最佳答案
因为 C++ 不允许 explained由 Prasoon 提供,因此另一种解决方案是使用 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;
关于c++ - 是否可以使用成员枚举来专门化模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4543720/