0

I have the following function declaration:

void get_data(struct myStruct* const value, const void * const data);

I have another function that I want to add a std::function as a parameter:

// I think the std::function definition is where my problem is
template<typename MyType>
void process(bool test, std::function<void(MyType* const, const void* const)>& callb) { ... }

However I can't quite figure out how to call it, or rather if my definition above is correct:

bool test1 = true;
process<myStruct>(test1, get_data);

Compiler Error:

error: prototype for ‘void process(bool, std::function<void(MyType* const, const void* const)>&)’ does not match any in class ‘MyClass’
 void process(bool test,
error: candidate is: template<class MyType> void process(bool, std::function<void(MyType*, const void*)>&)
     void process(bool test,
... goes on

Any ideas?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
arias_JC
  • 549
  • 3
  • 15

2 Answers2

2

You basically just have to remove the reference from the function object:

void process(bool test, std::function<void(MyType* const, const void* const)> callb);

While a reference to a std::function object cannot be related to/converted from the underlying function pointer type, the non-referenced object can be implicitely converted to the function pointer type thanks to its constructor.

Edit: Passing std::function as const reference gives no performance benefit, but may actually include some penalty in some corner cases, see Should I pass an std::function by const-reference?

Jodocus
  • 7,493
  • 1
  • 29
  • 45
1

When passing get_value to callb, the compiler has to construct a temporary std::function object for callb. But callb is declared as a non-const reference, which cannot be bound to a temporary object. So make callb be a const reference instead, which can be bound to a temporary:

template<typename MyType>
void process(bool test, const std::function<void(MyType* const, const void* const)>& callb) { ... }

Live Demo

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • this works as well, probably the better solution for my case – arias_JC Nov 07 '17 at 21:47
  • @arias_JC Not necessarily. In either way you end up calling the constructor of std::function, one time for a temporary (in this case) which you access then by const reference or one time for a function-local object. See also my edit. – Jodocus Nov 07 '17 at 21:55