gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:50:06 25 4
gpt4 key购买 nike

我有以下函数声明:

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

有什么想法吗?

最佳答案

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

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?

关于c++ - 使用 const void * 将 std::function 作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47167673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com