繁体   English   中英

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

[英]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是一个类,解决方案就是前面的类型名称。 枚举(或整数)是否有相当于它的东西?

由于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

用法也是非法的。 您提供了一个模板参数,但您需要提供两个参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM