【问题标题】:SFINAE tried with bool gives compiler error: "template argument ‘T::value’ involves template parameter" [duplicate]SFINAE 尝试使用 bool 给出编译器错误:“模板参数‘T::value’涉及模板参数”[重复]
【发布时间】:2011-12-08 06:04:53
【问题描述】:

我尝试使用 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”涉及模板参数

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

【问题讨论】:

    标签: c++ templates compiler-errors sfinae


    【解决方案1】:

    实际上,第 §14.5.4/9 节禁止您做的事情,

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

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

    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

    【讨论】:

    • 不错的解决方案。我已经编辑了一些部分和示例。对于我的具体要求,我想探索bool 技巧而不是void_ SFINAE 技巧。另外,如果它被标准禁止,我想我应该接受这个答案,因为我看不到任何其他出路。
    • 嗯,编辑没问题。我以为你可以使用bool2type 中的成员,这就是我添加它的原因。但如果你不需要它,那我完全没问题。
    • 啊,这正是我需要解决的问题。 Question 15115109 我通过使用 std::integral_constant 以及通过 type_traits 的 "::type" 成员直接可用的那些更进一步。
    • 我将相同的解决方案应用于我自己的应用程序。我处理将函数指针作为非类型模板参数的模板。在这里的问题的上下文中,解决方法是template&lt;auto&gt; struct value_to_type {}; template&lt;typename... T&gt; struct Resolve&lt;value_to_type&lt;my_function&lt;T...&gt;&gt;&gt; {...};
    • 现在您可以使用来自&lt;type_traits&gt;std::bool_constant 而不是拥有booltype
    猜你喜欢
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    相关资源
    最近更新 更多