【问题标题】:C++ extending initialization listC++ 扩展初始化列表
【发布时间】:2015-11-01 11:33:06
【问题描述】:

我希望能够使用通用外部函数以“人类可读”的形式显示不同的子类。在每个实例化中打印“数据”是微不足道的,但我正在努力寻找一种优雅的方式来打印每个对象内容的详细信息(元)。

我可以通过下面的AsDataFieldNamesGetFieldNames 三元组来实现我想要的。 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 FieldNames,例如:

const vector<string> A::FieldNames = {"NAME"};
const vector<string> B::FieldNames = ClassA::FieldNames + {"DESC"}; // Obviously not possible!

我也很乐意使用static const char* const FieldsConst[] 而不是vector&lt;string&gt;

我查看了this answerCRTP,但我认为它们不适合我的问题?

TIA :)

【问题讨论】:

  • 您能否简化代码以更好地概括您的问题?
  • 每个问题一个问题。
  • 感谢您的提示,我(希望)稍微简化了代码。

标签: c++ inheritance static overriding constants


【解决方案1】:

好的,我找到了一种方法 - 可以用 lamda 完成。线索在this question

要按照我的意愿初始化B::FieldNames,我应该使用:

const vector<string> B::FieldNames = [] 
    { vector<string> v = A::FieldNames; 
      v.push_back("DESC"); 
      return v; } ();

【讨论】:

    猜你喜欢
    • 2012-11-13
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多