本文介绍了是否可以使用成员枚举来专门化模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
是一个类,解决方案将是它前面的typename。
fails to compile using gcc 4.1.2It 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 ++允许的 Prasoon,所以一个替代的解决方案是使用 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的示例代码:
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;
这篇关于是否可以使用成员枚举来专门化模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!