不是c ++ 11
我需要用c ++编写一个工厂:
1)创建的元素是对象块
2)工厂保存对所有这些子对象的引用。
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*> members#
和members#.push_back(...)
的方式。
这可能吗? 这似乎是通过反射完成的,但我想要一些非反思的方式,静态地做这个。
感谢。
答案 0 :(得分:2)
以下可能会有所帮助:
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;