如何使用C ++中的某个语句初始化类const static结构

时间:2017-12-28 02:14:00

标签: c++ stl

属于一个类的const static std :: map。是否有一种形式可以形成以下代码:

// file A.h
class A {
   public:
           const static std::map<std::string, int> m_name2code;
   public:
           static int getCode(std::string name);
   private:
           const static char *name[3];
}

// file A.cpp
const char * A::name = {
            "hello", "the", "world" }
for (int index = 0; index < 3; ++index) {
        m_name2code.insert(std::string(name[i]), i+1);
}

作为上面的代码,我想知道是否有一些语法使用control-statement来初始化class-const-static成员?

非常感谢...

1 个答案:

答案 0 :(得分:3)

您将初始化分为两个阶段:

  1. 在函数中构建地图并返回结果。
  2. 从函数的结果初始化static变量。
  3. 例如:

    namespace {
        std::map<std::string, int> build_map() {
            std::map<std::string, int> rc;
            const char * A::name = { "hello", "the", "world" };
            for (int index = 0; index < 3; ++index) {
                rc.emplace(std::string(name[index]), index+1);
            }
            return rc;
        }
    }
    std::map<std::string, int> const A::m_name2code = build_map();
    

    如果你想更加想象,你甚至可以在编译时使用std::map初始化地图(虽然不是constexpr)(参见,例如,我的CppCon 2016年演示文稿:{ {3}})。