我有一些问题需要使用接口和工厂创建不同的线程:
我有两个派生的接口(这里是一个类但最终更多......)。我使用工厂来创建所需派生类的对象。 当我在不同的线程中运行它们时,我使用了工厂返回给出的作为线程构造函数的参数。
#include <iostream>
#include <thread>
class Base
{
public:
virtual ~Base () {}
virtual void operator () () = 0;
};
class Derived : public Base
{
public:
virtual void operator () ()
{
std::cout << "Derived of Base!" << std::endl;
}
};
enum BaseType
{
derived = 1000
};
class BaseFactory
{
public:
static Base *createBase (BaseType bt)
{
switch (bt)
{
case derived:
return new Derived;
default:
return NULL;
}
}
};
class OtherBase
{
public:
virtual ~OtherBase () {}
virtual void operator () () = 0;
};
class OtherDerived : public OtherBase
{
public:
virtual void operator () ()
{
std::cout << "OtherDerived of OtherBase!" << std::endl;
}
};
enum OtherBaseType
{
otherderived = 1100
};
class OtherBaseFactory
{
public:
static OtherBase *createOtherBase (OtherBaseType obt)
{
switch (obt)
{
case otherderived:
return new OtherDerived;
default:
return NULL;
}
}
};
int main (int argc, const char *argv[])
{
Base *pBase = BaseFactory::createBase(derived);
OtherBase *pOBase = OtherBaseFactory::createOtherBase(otherderived);
std::thread *t1 = new std::thread ((*pBase)());
std::thread *t2 = new std::thread ((*pOBase)());
t1->join();
t2->join();
delete t1;
delete t2;
return 0;
}
编译时,我在创建每个帖子时遇到问题:
test.cxx:87:50: error: invalid use of void expression
test.cxx:88:51: error: invalid use of void expression
我认为问题来自于我作为参数来创建类型为Base和OtherBase的线程对象(因此是接口)。 但是,我真的不知道如何解决这个问题。
答案 0 :(得分:2)
std::thread
的构造函数可以将成员函数指针作为第一个参数,并自动解除引用并在第二个参数上调用成员函数指针。
因此,你可以写:
std::thread *t1 = new std::thread (&Base::operator(), pBase);
std::thread *t2 = new std::thread (&OtherBase::operator(), pOBase);
这可能比使用std::bind
更简单。
答案 1 :(得分:1)
正如编译器所说 - 你要求创建一个参数设置为void的线程。
这是因为您通过(*pBase)()
调用了对象函数(operator())。
我想你需要创建一个绑定到适当对象的函数。您可以使用std :: bind执行此操作:
std::bind(&Base::operator(), pBase)
所以线程创建应该如下所示:
std::thread *t1 = new std::thread (std::bind(&Base::operator(), pBase));