我想达到类似的结果:
void somefunc(int var1, char var2){
dosomething();
}
int main(){
std::thread t1(somefunc, 'a', 3);
return EXIT_SUCCESS;
}
std::thread
接受一个函数指针和任意数量的参数。在我从 std::thread 派生的类中,我想用任意数量的参数初始化 std::thread 但我收到一条错误消息:
error: invalid conversion from ‘void (*)()’ to ‘void (*)(...)’ [-fpermissive]
Thread<> t1(funptr, 30);
但是当我删除标题中的点时,我得到链接器错误。我也希望能够在没有参数的情况下运行它。
我有以下代码(-stdc++17):
线程c.hpp
template </*typename Callable = void*,*/ typename... Args>
class Thread : public std::thread {
public:
Thread(void (*function)(...), int ms, Args... args)
:std::thread(/*std::forward<Callable>(function)*/function, ms, std::forward< Args >( args )...)
{
t_end = false;
}
~Thread(){
}
void End(){
t_end = true;
if(joinable()){
join();
}
}
private:
void executor(/*Callable function*/void (*function)(...), int ms, Args... args){
if(ms != 0){
while(!t_end){
(*function)(std::forward< Args >( args )...);
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
}
}else{
(*function)(std::forward< Args >( args )...);
}
if(joinable()){
join();
}
//std::async(std::launch::async, [] {
//});
}
bool t_end;
};
主.cpp:
void func1(){
dosomething();
}
void func2(int i){
dosomething();
}
int main(){
void (*funptr)() = &func1; // this step can be skipped still no result
Thread<> t1(funptr, 30); // doesnt work
Thread<int> t2(func2, 30, 3); // doesnt work
Thread t2(func2, 30, 3); // doesnt work I want to be able to skip the template parameters like in the std::thread function
return EXIT_SUCCESS;
}
如果有人可以帮助我,我将非常感激。我仍然是 C++ 初学者和高中生:)