c++ - 是否可以使用成员枚举来专门化模板?

标签 c++ templates enums template-specialization

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/

相关文章:

c++ - 如何在没有 WS_EX_LAYERED 的情况下在 C++ 中制作点击窗口

java - 在单独的包中使用嵌套枚举作为参数

java - 将域中的枚举包含到 gwt 共享类

基于枚举常量的 Typescript 排序

C++ 可变参数模板在虚拟抽象的外部未解析

c++ - 如何释放 V8 占用的内存?

c++ - 在包含对 cuda 内核的引用的库中链接

c++ - QT C++ - QNetworkAccessManager 需要帮助!类(Class)问题

templates - 在 helm 图表中附加 yaml anchor

templates - 无法在cloudstack上注册ISO或模板