我如何在下面实施?我想"预创建" 2" Doer" bool值的模板类实例。我坚持使用虚拟机吗?做这样的事最有效的方法是什么?我知道提升变体,但不确定它是否最好用?基本上我希望能够有2" Doer" bool值的模板,因为doer的各个成员将根据bool值采取不同的操作。
struct Config
{
int y;
};
template<typename DoerT>
class Aspect
{
public:
Aspect(bool b)
{
if(b) //can I create this way and pass around?
_doer<true>(this);
else
_doer<false>(this);
}
//will this work?
DoerT doer() const { return _doer;}
private:
DoerT _doer;
};
template<typename ConfigT, bool b>
class Doer
{
public:
//how to create typedef for Aspect and objects that need "b"
typedef Aspect<Doer<ConfigT,b> >* AspectT;
//also can I then specialize member functions of OtherObject
///based on b? There will be several other types here that
//will need to perform tasks differently based on the bool.
typedef OtherObject<ConfigT,b> OOT;
Doer(AspectT asp) : _asp(asp) {}
void doSomething(const Data& d)
{
}
private:
AspectT _asp;
OOT _obj;
};
//specialized members of Doer that need to behave differently based
//on bool..
template<Config,true> template<> Doer::doSomething {..}
template<Config,false> template<> Doer::doSomething {..}
template<typename DoerT>
class Manager
{
public:
typedef Aspect<DoerT>* AspectPtr;
void Load()
{
//retrieves data from database isNew returns bool
Data dbData = GetDataFromDB();
for(auto d : dbData)
{
//pass Boolean value to Aspect to create Doer templates
rows[dbData.Name]= new AspectPtr<DoerT>(d.IsNew());
}
}
AspectPtr Find(const std::string& name)
{
return rows[name];
}
private:
std::map<std::string,AspectPtr> rows;
};
class MXProcessor : Processor<Doer<Config, bool> > {...}
template<typename DoerT>
class Processor
{
public:
typedef Aspect<DoerT>* AspectPtr;
typedef OtherObject1<DoerT> obj1;
typedef OtherObject2<DoerT> obj2;
void start()
{
_mgr.Load();
}
void processData(const Data& d)
{
//lookup context row
AspectPtr asp = _ctxMgr.Find(d.Name);
asp->doer().doSomething(d);
}
private:
Manager<DoerT> _mgr;
LogMgr<DoerT> _lmgr;
};
int main() { //start MXProcessors}
答案 0 :(得分:0)
模板是一个编译时构造。你不能指望C ++会开箱即用。
实际上,使用代码生成,内省(在C ++中也不容易获得),编译和动态链接实际上是可能的。但你必须自己做。它不是语言。它也不会像模板那样微不足道。