SFINAE 尝试使用 bool 给出编译器错误:“模板参数‘T::value’涉及模板参数";

2021-12-31 00:00:00 compiler-errors templates c++ sfinae

我尝试使用 bool(不同于流行的 void_ 技巧):

 模板结构解析{静态常量布尔值 = 假;};模板struct Resolve{静态常量布尔值 = 真;};

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

struct B1 {//专门针对这种情况进行解析static const bool my_value = true;};struct B2 {//不特化static const bool my_value = false;};结构 B3 {};//不专业

当在 B1 上应用上述技巧时,它给出了编译错误:

解析::value;

<块引用>

错误:模板参数‘T::my_value’涉及模板参数

我知道这可以通过其他方式实现.但是,我很想知道,为什么它会在此处给出编译器错误,并且可以在此代码本身中解决吗?

解决方案

实际上你在做什么是第 §14.5.4/9 节禁止的,它说,

<块引用>

部分特化的非类型参数表达式不应涉及部分特化的模板参数,除非参数表达式是一个简单的标识符.

技巧也可以使用 type 作为第二个模板参数,封装 非类型 值,如下所述:

template结构布尔类型{};template>结构解析{静态常量布尔值 = 假;};模板struct Resolve>{静态常量布尔值 = 真;};

现在它编译罚款.

I tried to implement an SFINAE using bool (unlike popular 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;
  };

The goal is to specialize, the classes which have static const bool my_value = true; defined inside it. If they are defined false or not defined then don't specialize it. i.e.

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

When applying the above trick on B1 it gives the compilation error:

Resolve<B1>::value;

error: template argument ‘T::my_value’ involves template parameter(s)

I am aware that this can be achieved with alternate ways. However, I am interested in knowing, why it gives compiler error here and can it be solved in this code itself ?

解决方案

Actually what you're doing is forbidden by section §14.5.4/9 which says,

A partially specialized non-type argument expression shall not involve a template parameter of the partial specialization except when the argument expression is a simple identifier.

The trick could be using a type for second template parameter as well, encapsulating the non-type value, as described below:

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;
};

Now it compile fines.

相关文章