在非模板成员函数上使用 std::enable_if 时出错[重复]

问题描述 投票:0回答:2

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

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

当然 type 不是成员,它没有在这个通用版本的enable_if中定义,但这背后的整个想法不是如果bool为true则启用这个版本的fnc,如果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 enable-if
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"; }
};

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>()); }
    
© www.soinside.com 2019 - 2024. All rights reserved.