在C++中动态给出函数参数
Giving a function argument dynamically in C++
我有以下代码,我根据下面的 for 循环创建线程,pthread 中的第三个参数需要一个 void* (((void(,我给它一个字符串参数。问题是每个线程都有自己的方法,即线程 0 有它的方法 thread0((。我希望能够根据 for 循环的 t 设置方法而不会收到以下错误:
main2.cpp:40:51: error: cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘void* (*)(void*)’ for argument ‘3’ to ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)’ err = pthread_create(&threads[t], &attr,method, &t);
for(t = 0; t <5; t++){;
printf("Creating thread %dn",t);
std::string method = "thread"+t;
err = pthread_create(&threads[t], &attr,method, &t);
if(err != 0) exit(-1);
}
关于函数指针的错误消息非常清楚,您无法将 c++ 符号转换为字符串,反之亦然。
以下是文档中给出的pthread_create()
签名:
概要
int
pthread_create
(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
您可以执行以下操作:
typedef void* (*start_routine_t)(void*);
void* foo_0(void*) { return nullptr; }
void* foo_1(void*) { return nullptr; }
void* foo_2(void*) { return nullptr; }
void* foo_3(void*) { return nullptr; }
void* foo_4(void*) { return nullptr; }
constexpr std::map<std::string,start_routine_t> thread_funcs {
{ "thread_0" , foo_0 } ,
{ "thread_1" , foo_1 } ,
{ "thread_2" , foo_2 } ,
{ "thread_3" , foo_3 } ,
{ "thread_4" , foo_4 } ,
};
pthread_t threads[5];
// ....
for(t = 0; t <5; t++){;
printf("Creating thread %dn",t);
std::ostringstream method;
method << "thread_" <<t;
err = pthread_create(&threads[t], &attr,method, &thread_funcs[method.str()],nullptr);
if(err != 0) exit(-1);
}
或者更直接的方法根本不使用字符串:
start_routine_t thread_funcs[5] = { foo_0, foo_1, foo_2, foo_3, foo_4 };
pthread_t threads[5];
// ...
for(t = 0; t <5; t++){
printf("Creating thread %dn",t);
err = pthread_create(&threads[t], &attr,method, thread_funcs[t], nullptr);
if(err != 0) exit(-1);
}
正如您还要求 c++-11 设施:
- 直接使用
std::thread
而不是 pthread-API。如果目标环境正确支持 pthreads,则通常可以使用 ABIstd::thread
。 使用 lambda 函数动态引用特定例程:
std::vector<std::thread> threads(5); for(t = 0; t <5; t++){ printf("Creating thread %dn",t); auto thread_func = [t]() { switch(t) { case 0: foo_0(); break; case 1: foo_1(); break; case 2: foo_2(); break; case 3: foo_3(); break; case 4: foo_4(); break; } }; threads[t] = std::thread(thread_func); }
上面的代码示例可能不是最好的(最有效的(,但演示了如何动态映射函数调用。
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数