Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
                               ^
like image 852
ar2015 Avatar asked Nov 26 '25 12:11

ar2015


1 Answers

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).

like image 63
TemplateRex Avatar answered Nov 28 '25 03:11

TemplateRex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!