C ++智能工厂设计 [英] C++ Smart Factory Design
本文介绍了C ++智能工厂设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不是c ++ 11
我需要在c ++中编写一个像这样工作的工厂:
I need to write a Factory in c++ that works like so:
1)创建的元素是对象块
1) The elements created are blocks of objects
2)工厂保存对所有这些子对象的引用。
2) The factory saves references to all such sub-objects.
3)方块是可扩展的
含义:
class Block{
MemberType member1;
MemberType member2;
MemberType member3;
Block(){...}
}
class Factory{
set<MemberType*> members1;
set<MemberType*> members2;
set<MemberType*> members3;
Block& makeBlockInstance(){
Block& currentBlock = *(new Block());
members1.push_back(&(currentBlock.member1));
members2.push_back(&(currentBlock.member2));
members3.push_back(&(currentBlock.member3));
return currentBlock;
}
}
我需要的是一种添加或删除成员的方法 Block
,这样可以自动创建或删除 set< MemberType *>成员#
和成员#.push_back(...)
。
What I need is a way to add or remove members from Block
, in such a way that would AUTOMATICALLY create or delete the set<MemberType*> members#
, and the members#.push_back(...)
.
这可能吗?
这看起来像是通过反射做的事情,但我想要一些非反射的方式这样做,静态。
Is this possible? It seems like something that is done via reflection, but I want some non-reflection way of doing this, statically.
谢谢。 b $ b
推荐答案
以下可能有助于:
template<typename ... Ts> struct BlockFactoryT;
template<typename ... Ts>
struct BlockT
{
using Factory = BlockFactoryT<Ts...>;
BlockT(){...}
std::tuple<Ts...> members;
};
template<Ts...>
struct BlockFactoryT{
using Block = BlockT<Ts...>;
std::tuple<set<Ts*>> members_sets;
std::unique_ptr<Block> makeBlockInstance()
{
return makeBlockInstanceImpl(std::index_sequence_for<Ts...>());
}
template<std::size_t ... Is>
std::unique_ptr<Block> makeBlockInstanceImpl(std::index_sequence<Is...>)
{
auto block = std::make_unique<Block>();
const int dummy[] = {0,
(std::get<Is>(members_sets).insert(&std::get<Is>(block->members)), 0)...};
static_cast<void>(dummy); // Remove warning for unused variable
return block;
}
};
为了简单起见:
using MyBlock = BlockT<MemberType, MemberType, MemberType2>;
using MyFactory = typename MyBlockT::Factory;
这篇关于C ++智能工厂设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文