【问题标题】:Problem with SFINAESFINAE 的问题
【发布时间】:2010-11-12 12:45:17
【问题描述】:

为什么 SFINAE 规则无法解析此代码(M 类中的 fnc 值)?我收到一个错误:

Error   1   error C2039: 'type' : is not a member of
                                   'std::tr1::enable_if<_Test,_Type>'  

当然 type 不是成员,它没有在 enable_if 的这个通用版本中定义,但是如果 bool 为 true 并且不实例化它,如果 bool 为 true 并且不实例化它,这不是背后的全部想法吗?有人可以向我解释一下吗?

#include <iostream>
#include <type_traits>

using namespace std;

template <class Ex> struct Null;
template <class Ex> struct Throw;

template <template <class> class Policy> struct IsThrow;

template <> struct IsThrow<Null> {
    enum {value = 0};
};

template <> struct IsThrow<Throw> {
    enum {value = 1};
};

template <template <class> class Derived>
struct PolicyBase {
    enum {value = IsThrow<Derived>::value};
};

template<class Ex>
struct Null : PolicyBase<Null> { };

template<class Ex>
struct Throw : PolicyBase<Throw> { } ;

template<template< class> class SomePolicy>
struct M {

  //template<class T>
  //struct D : SomePolicy<D<T>>
  //{
  //};
  static const int ist = SomePolicy<int>::value;
  typename std::enable_if<ist, void>::type value() const
  {
    cout << "Enabled";
  }

  typename std::enable_if<!ist, void>::type value() const
  {
    cout << "Disabled";
  }
};

int main()
{
    M<Null> m;
    m.value();
}

【问题讨论】:

    标签: c++ templates sfinae


    【解决方案1】:

    SFINAE 不适用于非模板函数。相反,您可以例如使用(类的)特化或基于重载的调度:

    template<template< class> class SomePolicy>
    struct M
    {
        static const int ist = SomePolicy<int>::value;        
        void value() const { 
            inner_value(std::integral_constant<bool,!!ist>()); 
        }
     private:
        void inner_value(std::true_type) const { cout << "Enabled"; }
        void inner_value(std::false_type) const { cout << "Disabled"; }
    };
    

    【讨论】:

      【解决方案2】:

      这里没有没有sfinae

      在已知M&lt;Null&gt; 之后,变量ist 也已知。 那么std::enable_if&lt;ist, void&gt; 也很明确。 您的功能之一没有明确定义。

      SFINAE 仅适用于模板函数的情况。 模板函数在哪里?

      把你的代码改成

      template<int> struct Int2Type {}
      
      void value_help(Int2Type<true> ) const { 
          cout << "Enabled"; 
      } 
      
      void value_help(Int2Type<false> ) const { 
          cout << "Disabled"; 
      } 
      
      void value() const { 
          return value_help(Int2Type<ist>());
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-19
        • 1970-01-01
        • 2021-06-05
        相关资源
        最近更新 更多