我发现了 std::function
和类型推导的以下行为,这对我来说是出乎意料的:
#include <functional>
template <typename T>
void stdfunc_test(std::function<T(T)> func) {};
int test_func(int arg)
{
return arg + 2;
}
int main()
{
stdfunc_test([](int _) {return _ + 2;});
stdfunc_test(test_func);
}
main
中的两行都会导致错误:
no instance of function template "stdfunc_test" matches the argument list
尝试在 Visual Studio 2015 中编译时。
为什么类型推导不从函数类型中推导模板类型,是否有解决方法?
最佳答案
您可以使用模板来推导函数和仿函数的签名:
#include<functional>
template<class T>
struct AsFunction
: public AsFunction<decltype(&T::operator())>
{};
template<class ReturnType, class... Args>
struct AsFunction<ReturnType(Args...)> {
using type = std::function<ReturnType(Args...)>;
};
template<class ReturnType, class... Args>
struct AsFunction<ReturnType(*)(Args...)> {
using type = std::function<ReturnType(Args...)>;
};
template<class Class, class ReturnType, class... Args>
struct AsFunction<ReturnType(Class::*)(Args...) const> {
using type = std::function<ReturnType(Args...)>;
};
template<class F>
auto toFunction( F f ) -> typename AsFunction<F>::type {
return {f};
}
template <typename T>
void stdfunc_test(std::function<T(T)> func) {};
int test_func(int arg)
{
return arg + 2;
}
int main()
{
stdfunc_test( toFunction([](int _) {return _ + 2;}) );
stdfunc_test( toFunction(test_func) );
return 0;
}
您可以在这里现场试用:http://fiddle.jyt.io/github/d4ab355eb2ab7fc4cc0a48da261f0127
关于c++ - 使用 std::function 进行模板类型推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39173519/