I am trying to write function func
so that compiler can deduce template argument, it works when I pass in std::function
, but does not work with lambdas:
template<typename TResult>
TResult func(std::function<TResult()> f)
{
return TResult();
}
int main()
{
// Visual Studio 2013
int result = func([]() { // error: 'TResult func(std::function<TResult(void)>)' : could not deduce template argument for 'std::function<TResult(void)>' from 'main::<lambda_d9d7854806072a2cb711f56185602ccb>'
return 100;
});
std::function<int()> testFunc = []() {
return 100;
};
int result2 = func(testFunc); // this works
return 0;
}
Is it possible to deduce template argument for lambda so that this line compiles? Instead of writing func<int>([](){ return 100; });
I want to write func([](){ return 100; });
I'm late a little bit :)
There is a solution without std::function
template<typename Class, typename R, typename... Args>
R resultType(R (Class::*)(Args...) const)
{
return R();
}
template<typename Class, typename R, typename... Args>
R resultType(R (Class::*)(Args...))
{
return R();
}
template<typename Functor>
auto func(Functor f) -> decltype(resultType(&Functor::operator()))
{
return resultType(&Functor::operator());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With