Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deduce template argument when lambda passed in as a parameter

Tags:

c++

c++11

lambda

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; });

like image 332
Piotr Wach Avatar asked Jan 20 '14 22:01

Piotr Wach


1 Answers

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());
}
like image 178
alexeibs Avatar answered Sep 22 '22 14:09

alexeibs