SFINAE +类型特征的自动类型推断失败

时间:2017-11-23 18:26:55

标签: c++ c++11 templates

这个最小的可编译示例似乎是SFINAE的非常标准的设置:

#include <type_traits>

struct AType{};

// Helper type-trait templates for AType
template<typename T> struct isAType{ static const bool value = false; };
template<> struct isAType<AType>{ static const bool value = true; };

template<typename T>
void function( typename std::enable_if<isAType<T>::value, T>::type& t 
) {}

int main()
{
  AType a1;

  // This line, using automatic type deduction, fails to compile:  
  // function( a1 );

  // If you manually specify template parameter, it compiles:
  function<AType>( a1 );
}

取消注释function( a1 );时,我收到的错误消息如下:

main.cpp: In function ‘int main()’:
main.cpp:17:16: error: no matching function for call to ‘function(AType&)’
   function( a1 );
                ^
main.cpp:10:6: note: candidate: template<class T> void function(typename 
std::enable_if<isAType<T>::value, T>::type&)
 void function( typename std::enable_if<isAType<T>::value, T>::type& t ) 
{}
      ^
main.cpp:10:6: note:   template argument deduction/substitution failed:
main.cpp:17:16: note:   couldn't deduce template parameter ‘T’
   function( a1 );

我看到some posts表示“T”处于非受限的上下文中。 “非弱化背景”对我来说是一个新概念,但足够的墨水已经渗透到其他地方,我可以弄明白。我想,我的问题是,我的function声明是否可以通过自动类型演绎成功的方式进行调整。是否有规范的方法来实现具有类型特征的SFINAE,以便自动类型推导成功?

1 个答案:

答案 0 :(得分:1)

并非所有的C ++编译器都支持它,但如果你这样做,这是最干净的方法:

template<bool b>
using sfinae = typename std::enable_if< b, bool >::type;

template<class T,
  sfinae<isAType<T>::value> =true
>
void function( T& t  )
{
}
中的

我不会为sfinae别名烦恼,但摆脱typename会使值得。{/ p>

请注意,=true部分是必需的,但如果是=false则意味着同样的事情。

这里发生的是我们定义一个非类型模板参数,其类型仅在测试通过时才存在。然后我们给它一个默认值。

我发现这种技术读取最像传入的我的意思我的意思是 C ++的概念特征。