C++扩展初始化列表
问题描述:
我希望能够使用公共外部函数以“人类可读”形式显示不同的子类。在每个实例化中打印'数据'是微不足道的,但我正在用一种优雅的方式来打印关于每个对象内容的细节(元)。C++扩展初始化列表
我可以达到我想要的以下三重AsData
,FieldNames
和GetFieldNames
。 AsData
封装在一个可读形式的会员资料,FieldNames
存储在层次结构该点的数据字段名称类的静态列表和GetFieldNames
包装FieldNames
具有可继承功能:
class A {
public:
A(const string& name) { /* Setup data */ }
// ... functions to access data members go here ...
virtual const vector<string>& GetFieldNames() {
return A::FieldNames;
}
protected:
static const vector<string> FieldNames;
// ... some data members ...
};
class B : public A {
public:
B(const string& name, const string& description): A (name) { /* Setup extended data */ }
// ... functions to access additional data members go here ...
virtual const vector<string>& GetFieldNames() {
return B::FieldNames;
}
protected:
static const vector<string> FieldNames;
// ... some additional data members ...
};
所以使用可如下:
void PrintTable (vector<shared_ptr<A> >& objects) {
// Print the field names.
for(const string& name : objects.front()->GetFieldNames())
cout << name << "\t";
// ... code to print the actual data goes here ...
}
int main(int argc, char **argv) {
vector<shared_ptr<A> > myObjects;
myObjects.push_back(make_shared<B>("Box", "Storage container"));
myObjects.push_back(make_shared<B>("Glass", "Drink container"));
PrintTable (myObjects);
return 0;
}
我想问一下,如果它可以覆盖一个静态const成员,并延长它(我知道这听起来有些矛盾),所以我可以添加字段静态常量字段名,即东西如:
const vector<string> A::FieldNames = {"NAME"};
const vector<string> B::FieldNames = ClassA::FieldNames + {"DESC"}; // Obviously not possible!
我也很乐意使用static const char* const FieldsConst[]
而不是vector<string>
。
我看过this answer和CRTP但我认为它们不符合我的问题?
TIA :)
答
好吧,我已经找到一种方法 - 它可以与LAMDA来完成。线索在this question。
初始化B::FieldNames
因为我想,我应该使用:
const vector<string> B::FieldNames = []
{ vector<string> v = A::FieldNames;
v.push_back("DESC");
return v; }();
您可以简化代码,以便更好地勾勒出你的问题吗? – davestevens
每个问题请提出一个问题。 –
谢谢你的提示,我有(希望)简化了一下代码。 – iwbnwif