das folgende Stück Code zu haben:Warum std :: is_function gibt false für einfache Funktionen und Lambdas zurück?
#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
}
ich die folgende Fehlermeldung erhalten:
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<
^
Wenn ich die std::enable_if
Template-Parameter kommentieren Sie dann kompiliert und läuft gut. Warum?
'std :: is_function' prüft nur auf Funktionstypen, die keine lambdas enthalten. Gibt es einen Grund, warum Sie SFINAE verwenden müssen? Wenn Sie wirklich die Überprüfung durchführen möchten, können Sie überprüfen, ob 'f (3)' wohlgeformt ist, anstatt zu überprüfen, ob 'f' funktional ist. – TartanLlama
Sieht so aus, als ob Sie tatsächlich nach etwas wie [' std :: is_callable'] (http://en.cppreference.com/w/cpp/types/is_callable), das mit C++ 17 verfügbar ist, aber "kann in Bezug auf' std :: is_convertible' und 'std :: result_of' "mit reinem C++ 11. – m8mble
@TartanLlama Wie würden Sie prüfen, ob 'f (3)' gut gebildet ist? – Patryk