c++ - 模板参数推导失败,SFINAE

标签 c++ templates sfinae

当我编译这段代码时:

#include <type_traits>

template <typename T>
void do_stuff(std::enable_if_t<std::is_integral<T>::value, T> &t) {}

template <typename T>
void do_stuff(std::enable_if_t<std::is_class<T>::value, T> &t) {}

int main() {
    int i = 1;
    do_stuff(i);
    return 0;
}

海湾合作委员会说:

37325975.cpp: In function ‘int main()’:
37325975.cpp:11:15: error: no matching function for call to ‘do_stuff(int&)’
     do_stuff(i);
               ^
37325975.cpp:4:6: note: candidate: template<class T> void do_stuff(std::enable_if_t<std::is_integral<_Tp>::value, T>&)
 void do_stuff(std::enable_if_t<std::is_integral<T>::value, T> &t) {}
      ^
37325975.cpp:4:6: note:   template argument deduction/substitution failed:
37325975.cpp:11:15: note:   couldn't deduce template parameter ‘T’
     do_stuff(i);
               ^
37325975.cpp:7:6: note: candidate: template<class T> void do_stuff(std::enable_if_t<std::is_class<T>::value, T>&)
 void do_stuff(std::enable_if_t<std::is_class<T>::value, T> &t) {}
      ^
37325975.cpp:7:6: note:   template argument deduction/substitution failed:
37325975.cpp:11:15: note:   couldn't deduce template parameter ‘T’
     do_stuff(i);
           ^

我也试过 msvc 2013。

为什么会出现这些错误?

Live Demo

最佳答案

正如编译器所说,该参数类型是不可推导的,因此您需要手动提供模板参数,如下所示:

do_stuff<int>(i);

更好的选择是将 std::enable_if 放在返回类型或模板参数列表中:

//Return type
template <typename T>
std::enable_if_t<std::is_integral<T>::value>
do_stuff(T &t) {}

template <typename T>
std::enable_if_t<std::is_class<T>::value> 
do_stuff(T &t) {}

//Parameter list
template <typename T, std::enable_if_t<std::is_integral<T>::value>* = nullptr>
void do_stuff(T &t) {}

template <typename T, std::enable_if_t<std::is_class<T>::value>* = nullptr > 
void do_stuff(T &t) {}

这样仍然可以推导出模板参数:

do_stuff(i);

关于c++ - 模板参数推导失败,SFINAE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37325975/

相关文章:

python - Django Python - 如何在一个 HTML 模板中显示来自不同表格的信息

c++ - 将右值作为右值转发是用例吗?

c++ - SFINAE 为什么我没有检测到 std::vector 的下标运算符?

c++ - 使用 "--enable-vtable-verify"构建 Devtoolset 7 gcc

c++ - C++ 中的高斯积分不起作用。为什么?

c++ - QT什么时候不允许一行多次转换,比如QString to char*

c++ - SFINAE 未能处理中间类型特征

JavaScript 获取数组大小效率

c++ - 静态检查 const char* 包含空格

c++ - 模板函数参数显式类型声明