是否可以使用成员枚举专门化一个模板? [英] Is it possible to specialize a template using a member enum?
问题描述
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
是一个类,解决方案将是它前面的一个类型名称。是否有与枚举(或整数)相当的东西?
fails to compile using gcc 4.1.2
It complains about the usage of T::Special
for partial specilization of Foo. If Special
was a class the solution would be to a typename in front of it. Is there something equivalent to it for enums (or integers)?
推荐答案
由于C ++不允许解释,所以一个替代解决方案是使用 EnumToType
类模板
Since that is not allowed by C++ as explained by Prasoon, so an alternative solution would be to use EnumToType
class template,
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
Sample code at ideone : http://www.ideone.com/JPvZy
或你可以这样专门化(如果它解决了你的问题),
Or, you can simply specialize like this (if it solves your problem),
template<class T> struct Foo<T,Bar::Special> {};
//usage
Foo<Bar, Bar::Special> f;
这篇关于是否可以使用成员枚举专门化一个模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!