SFINAE尝试使用bool给出了编译器错误:“模板参数'T :: value'涉及模板参数”

时间:2011-10-15 07:28:28

标签: c++ templates compiler-errors sfinae

我尝试使用bool实现SFINAE(与流行的void_ trick不同):

  template<typename T, bool = true>
  struct Resolve
  {
    static const bool value = false;
  };

  template<typename T>
  struct Resolve<T, T::my_value>
  {
    static const bool value = true;
  };

目标是专门化,在其中定义static const bool my_value = true;的类。如果定义false或未定义,则不要专门化它。即。

struct B1 {  // specialize Resolve for this case
  static const bool my_value = true;
};
struct B2 {  // don't specialize
  static const bool my_value = false;
};
struct B3 {};  // don't specialize

B1上应用上述技巧时,会出现编译错误:

Resolve<B1>::value;
  

错误:模板参数'T :: my_value'涉及模板参数

我知道这可以通过其他方式实现。但是,我有兴趣知道,为什么它在这里给编译器错误,并且可以在这段代码中解决它?

1 个答案:

答案 0 :(得分:23)

实际上,§14.5.4/ 9部分禁止你所做的事情,

  

部分专用的非类型参数表达式不应包含部分特化的模板参数,除非参数表达式是简单标识符。

诀窍可能是使用类型作为第二个模板参数,封装非类型值,如下所述:

template<bool b> struct booltype {};

template<typename T, typename B = booltype<true> >
struct Resolve
{
  static const bool value = false;
};

template<typename T>
struct Resolve<T, booltype<T::my_value> >
{
  static const bool value = true;
};

现在compile fines

相关问题