【发布时间】:2016-06-21 14:08:09
【问题描述】:
有以下代码:
#include <iostream>
#include <type_traits>
template <typename F,
typename = typename std::enable_if<
std::is_function< F >::value
>::type>
int fun( F f ) // line 8
{
return f(3);
}
int l7(int x)
{
return x%7;
}
int main()
{
auto l = [](int x) -> int{
return x%7;
};
fun(l); // line 23
//fun(l7); this will also fail even though l7 is a regular function
std::cout << std::is_function<decltype(l7)>::value ; // prints 1
}
我会得到以下错误:
main2.cpp: In function ‘int main()’:
main2.cpp:23:8: error: no matching function for call to ‘fun(main()::<lambda(int)>&)’
fun(l);
^
main2.cpp:8:5: note: candidate: template<class F, class> int fun(F)
int fun( F f )
^
main2.cpp:8:5: note: template argument deduction/substitution failed:
main2.cpp:5:11: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
typename = typename std::enable_if<
^
当我注释掉 std::enable_if 模板参数时,它编译并运行得很好。为什么?
【问题讨论】:
-
std::is_function仅检查不包括 lambdas 的函数类型。您是否有理由需要使用 SFINAE?如果你真的想做检查,你可以检查f(3)是否格式正确,而不是检查f是否类似于函数 -
看起来您实际上是在寻找类似 @987654321@ 的东西,它可以在 C++17 中使用,但“可以用纯 C++ 实现
std::is_convertible和std::result_of” 11. -
@TartanLlama 你如何检查
f(3)的格式是否正确? -
@Patryk 类似this。这是expression SFINAE。
标签: c++ c++11 lambda template-meta-programming typetraits