Compute template argument when lambda passed as parameter

I am trying to write a function funcso that the compiler can output a template argument, it works when I go in std::function, but it 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 infer a template argument for lambda so that this string compiles? Instead of writing, func<int>([](){ return 100; });I want to writefunc([](){ return 100; });

+4
source share
4 answers

I cannot immediately see how to do this, but you can do this in an indirect area:

template <typename TResult>
TResult func(std::function<TResult()> f) {
    return TResult();
}

template <typename Fun>
auto func(Fun f) -> decltype(f()) {
    return func(std::function<decltype(f())>(f));
}
+4
source

I'm a little late :) 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());
}
+5
source

, , , :

template <class F>
auto foo(F &&f) -> decltype(f()) {
    typedef decltype(f()) ret_type;
    return ret_type();
}

... typedef:

template <class F>
auto foo(F &&f) -> decltype(f()) {
    return decltype(f())();
}

, :

#include <functional>
#include <iostream>

template <class F>
auto foo(F &&f) -> decltype(f()) {
    return decltype(f())();
}

template<typename TResult>
TResult func(std::function<TResult()> f) {
    return TResult();
}

int main() {
   std::cout << foo([]() { return 100; })<<"\n";

    std::function<int()> testFunc=[]() { return 100; };
    std::cout << func(testFunc) <<"\n"; // this works

    return 0;
}

Results:

0
0
+2
source

No, you cannot use it std::functionhere, the compiler cannot output arguments of its type.

You should just pass the parameter as TFunction.

+1
source

All Articles