【发布时间】:2015-06-25 06:15:57
【问题描述】:
我在使用接口和工厂创建不同的线程时遇到了一些问题:
我有两个派生的接口(这里是一个类,但最终更多......)。我使用工厂来创建所需派生类的对象。 当我在不同的线程中运行它们时,我使用工厂返回给我的作为线程构造函数的参数。
#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 类型的线程对象(因此是接口)。 但是我真的不知道如何解决这个问题。
【问题讨论】:
-
您是在调用函子,而不是将它们传递给要调用的线程。
标签: c++ multithreading interface functor