【发布时间】:2019-01-13 14:19:48
【问题描述】:
我有一个基类,它的构造函数接收一个名为 id 的 int 类型,以及几个不同的派生类,它们的构造函数形式与基类相同。
现在我想创建一个包含每个元素的元组,它的构造函数接收一个由它在这个元组中的索引确定的 id。就像下面的哑函数一样:
class Base(){
Base(int id){}
}
class Derive1, Derived2...Derivedn : public Base(){
Derive(int id):Base(id){}
}
auto make_derives_tuple()->decltype(...){
//manually write each elements' index in the tuple seems too ugly and unnecessary
return std::make_tuple(Derive1(0),Derived2(1),Derived3(2)...);
}
如果派生类的个数是三个:
struct Base{
Base(int id){
id_=id;
}
int id_;
};
struct Derive:public Base{
Derive(int id):Base(id){
}
};
struct Derive2:public Base{
Derive2(int id):Base(id){
}
};
auto make_derive_tuple()->decltype (std::make_tuple(Derive(0),Derive2(1),Derive3(2))){
//I want the int passed to the derived class's construor automatically generated according to it's position in the tuple
return std::make_tuple(Derive(0),Derive2(1),Derive3(2));
}
但是在元组中手动编写每个元素的索引以传递给构造函数似乎太丑陋且没有必要。有什么优雅的方法可以实现这一目标吗?就像使用可变参数模板类或函数一样。
【问题讨论】:
-
即使只包含两个派生类,您能否提供实际的示例代码?上面的草图不是很清楚,因为它不符合 C++ 语法。
标签: c++ templates variadic-templates template-meta-programming stdtuple