C++ std::vector 作为 std::function 的参数
C++ std::vector as Parameter for std::function
>我试图在C++中进行回调。回调的参数是通过引用传递的向量。问题是当我调用函数时,向量总是空的。要演示这一点,请参阅下面的程序。
struct TestStruct {
int x;
int y;
};
void TestFunction( const std::vector<TestStruct> &vect ) {
for ( unsigned int i = 0; i < vect.size(); i++ ) {
printf( "%i, %in", vect[ i ].x, vect[ i ].y );
}
}
int main() {
std::map<std::string, std::function<void( const std::vector<TestStruct>& )>> map;
std::vector<TestStruct> vect;
map[ "test1" ] = std::bind( &TestFunction, vect );
map[ "test2" ] = std::bind( &TestFunction, vect );
std::vector<TestStruct> params;
TestStruct t;
t.x = 1;
t.y = 2;
params.emplace_back( t );
map[ "test1" ]( params );
}
这是我能给出的最接近我正在做的事情的例子。我已经将回调保存在地图中。然后,我将函数添加到地图中。然后我做一个通用的TestStruct并把它放在我的参数中。最后,我调用该函数,它应该打印出"1,2",但不打印任何内容。
当我调试它时,它说参数为空。这让我相信我做错了什么,或者这是不可能的。
那么这里出了什么问题呢?任何帮助或提示将不胜感激。谢谢。
当你写:
map[ "test1" ] = std::bind( &TestFunction, vect );
这为您提供了一个空函数,当调用该函数时,它会为您提供TestFunction(vect)
的结果。您正在将vect
绑定到 TestFunction
的第一个参数。因此,当您调用它时,您正在打印vect
中的内容(为空)的结果,而不是params
中的内容(不是)。
这根本不是你想要的 - 你想要实际的功能TestFunction
:
map[ "test1" ] = TestFunction;
<小时 />你会认为这不会编译。毕竟,你想要一个接受参数的函数,但你给了它一个不接受参数的函数。但是bind()
只是忽略了它不使用的所有参数。
您不需要使用空vector
bind
TestFunction
。您可以直接将其添加到地图中。
map[ "test1" ] = TestFunction;
map[ "test2" ] = TestFunction;
相关文章:
- Confusion: decltype vs std::function
- 为什么 std::function 可以作为 std::not2 的参数?
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- 传递给std::function template的template参数究竟代表什么
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 将函数包装器转换为 std::function
- 类型擦除的std::function与虚拟函数调用的开销
- C++ std::function 对于类 exept 的所有实例都是空的(只有 Visual2019 编译器问题)
- 如果模板没有可变参数,则 Lambda 被推导出为 std::function
- 将 lambda 表达式传递给 std::function in C++
- 模板类的部分模板专用化,如 std::function
- 可变参数模板参数扩展 类型为 std::function 的类成员
- 从 std::function in C++ 访问模板化 lambda
- 什么是 std::function::argument_type 的替代品?
- C++派生类重载函数(带有 std::function 参数)不可见
- 如何在 qi 符号表中使用 std::function
- 将 std::function 与模板一起使用
- C++ 事件管理器的回调,使用 std::function 和 std:bind 以及派生类作为参数
- 我需要在 std::function 上使用 unique_ptr 吗?
- 如何将函数指针从 std::function 传递到 Linux 克隆?