本文介绍了SFINAE 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个代码(M 类中的 fnc 值)没有被 SFINAE 规则解析?我收到一个错误:

Why this code (fnc value in class M) do not get resolved by SFINAE rules? I'm getting an error:

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

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

Of course type is not a member, it isn't defined in this general ver of enable_if but isn't the whole idea behind this to enable this ver of fnc if bool is true and do not instantiate it if it's false? Could please someone explain that to me?

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

推荐答案

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

SFINAE does not work for non-template functions. Instead you can e.g. use specialization (of the class) or overload-based dispatching:

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

这篇关于SFINAE 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 01:26