Search code examples
c++c++11templatesstd-function

std::function and error: no matching function for call to


I am calling a template based function which shares a type between a function and structure. What is wrong with this code? why do I receive error when I compile it?

test.cpp

#include <functional>
#include <iostream>

template<typename T>
struct mystruct
{
    T variable;
};

int myfunc(int x)
{
    return 2*x;
}

template<typename T>
T calculate(
    mystruct<T> custom_struct,
    std::function<T(T)> custom_func)
{
    return custom_func(custom_struct.variable);
}

int main()
{
    mystruct<int> A;
    A.variable=6;
    std::cout<<calculate(A,myfunc)<<std::endl;
    return 0;
}

Compiler results:

test.cpp:25:31: error: no matching function for call to ‘calculate(mystruct<int>&, int (&)(int))’
  std::cout<<calculate(A,myfunc)<<std::endl;
                               ^

Solution

  • There is no reason to use the std::function wrapper. Instead use a general template parameter F

    template<typename T, class F>
    T calculate(
        mystruct<T> custom_struct,
        F custom_func)
    {
        return custom_func(custom_struct.variable);
    }
    

    Live Example

    Note that you also forgot to access the variable member at the call site. Since you are doing generic programming here, you also want the return type to be equal to T, or even auto (C++14, for C++11 you want probably use decltype but that is too much repetition).