5

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

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

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

#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();
}
4

2 回答 2

5

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"; }
};
于 2010-11-12T12:57:41.547 回答
3

这里没有sfinae

在已知之后M<Null>,变量ist也是已知的。然后std::enable_if<ist, void>也很明确。您的功能之一没有明确定义。

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>());
}
于 2010-11-12T12:55:36.617 回答