使用const void *将std :: function作为参数传递

时间:2017-11-07 21:25:15

标签: c++ c++11

我有以下函数声明:

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

我有另一个功能,我想添加std::function作为参数:

// 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) { ... }

但是,我无法弄清楚如何调用它,或者更确切地说,如果我上面的定义是正确的:

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

编译器错误:

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

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您基本上只需要从函数对象中删除引用:

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

虽然对std::function对象的引用无法与基础函数指针类型相关/转换,但由于其构造函数,未引用的对象可以被隐式转换为函数指针类型。

编辑:将std::function作为const引用传递不会带来任何性能优势,但实际上可能会在某些极端情况下包含一些惩罚,请参阅Should I pass an std::function by const-reference?

答案 1 :(得分:1)

get_value传递给callb时,编译器必须为std::function构造一个临时callb对象。但callb被声明为非const引用,不能绑定到临时对象。因此,将callb改为const引用,它可以绑定到临时引用:

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

Live Demo

相关问题