gpt4 book ai didi

具有可变函数参数的 C++ 多态性

转载 作者:搜寻专家 更新时间:2023-10-31 01:11:23 25 4
gpt4 key购买 nike

我正在与您分享我在使用可变函数参数的类中遇到的一个问题。它是下面代码中显示的类 Thread。它是 std::thread 的包装器,以便使用函数模式。

我想对这个函数使用多态性,将类 Thread 继承到一个新类 Functor 中,但是 gcc 返回以下错误:

#include <thread>
#include <iostream>

using namespace std;

template<class... Args>
class Thread
{
public:
virtual void operator()(Args...) = 0;

void run(Args... args)
{
std::thread t(std::forward< Thread<Args...> >(*this), std::forward<Args>(args)...);
t.join();
}
};

template<class... Args>
class Functor : public Thread<Args...>
{
public:
// generates the errors bellow
virtual void operator()(Args... /*args*/)
{
}

// doesnot work since the pure virtual function wants another prototype of function.
// void operator()(int)
// {
// }
};

int main()
{
int a = 12;
Functor<int> f;
f.run(ref(a));

return 0;
}
from t-Thread-args2.cpp:1:/usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.2/../../../../include/c++/4.7.2/tuple: In instantiation of ‘struct std::_Head_base, false>’:/usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.2/../../../../include/c++/4.7.2/tuple:215:12:   required from ‘struct std::_Tuple_impl, int>’/usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.2/../../../../include/c++/4.7.2/tuple:507:11:   required from ‘class std::tuple, int>’/usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.2/../../../../include/c++/4.7.2/functional:1601:39:   required from ‘struct std::_Bind_simple(int)>’/usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.2/../../../../include/c++/4.7.2/thread:133:9:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = Thread; _Args = {int}]’t-Thread-args2.cpp:14:83:   required from ‘void Thread::run(Args ...) [with Args = {int}]’t-Thread-args2.cpp:42:17:   required from here/usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.2/../../../../include/c++/4.7.2/tuple:166:13: error: cannot declare field ‘std::_Head_base, false>::_M_head_impl’ to be of abstract type ‘Thread’t-Thread-args2.cpp:7:7: note:   because the following virtual functions are pure within ‘Thread’:t-Thread-args2.cpp:10:18: note:     void Thread::operator()(Args ...) [with Args = {int}]

我不太明白这个错误,因为纯虚函数在派生类中定义得很好。但是,在将函数 run() 移动到派生类 (Functor) 时,它起作用了。

提前致谢,蚕儿

最佳答案

根据 [thread.thread.constr]§3,std::thread 构造函数的第一个参数的类型是 F&&,要求 FMoveConstructible。在您的例子中,FThread,它不是 MoveConstructible

换句话说,std::thread 需要按值存储仿函数,而您将仿函数作为抽象的 Thread 转发。

关于具有可变函数参数的 C++ 多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14996945/

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