【问题标题】:C++ auto deducing not working in class constructorC ++自动推断在类构造函数中不起作用
【发布时间】:2020-12-15 13:01:22
【问题描述】:

我有两个班级:

class string_keys_management {
public:
    string_keys_management(const string_keys_management&) = default;
    string_keys_management(string_keys_management&&) = default;
    string_keys_management& operator=(const string_keys_management&) = default;
    string_keys_management& operator=(string_keys_management&&) = default;
    string_keys_management(const std::initializer_list<std::string>& keys, const std::string &description = "") : keys(keys), description(description) {}
    bool operator==(const std::string &ref) { /*...*/ }
    bool operator!=(const std::string &ref) { /*...*/ }
    bool operator<(const string_keys_management &ref) const { /*...*/ }

private:
    std::vector<std::string> keys;
    std::string description;
};

template <typename V>
class multimap {
public:
    multimap(const std::map<string_keys_management, V> &ref) : values(ref) {}
    multimap& operator=(const std::map<string_keys_management, V> &ref) { values = ref; }
    V& at(const std::string &key) { return values.at(key); }
    void insert(const string_keys_management &keys, V val) { values.insert({keys, val}); }

private:
    std::map<string_keys_management, V> values;
};

当我尝试创建 multimap 实例时,当我试图让编译器推断类型时遇到麻烦:

int main() {
    multimap<std::string> mp = {
            {{{"key1", "key2", "key3"}, "description1"}, "value"},
            {{{"key4", "key5", "key6"}, "description1"}, "value2"}
    };
    return EXIT_SUCCESS;
}

它的最短工作方式是:

multimap<std::string> mp = std::map<string_keys_management, std::string>{
        {{{"key1", "key2", "key3"}, "description1"}, "value"},
        {{{"key4", "key5", "key6"}, "description1"}, "value2"}
};

编译器:G++-10.2 C++20。

这是预期的方式,还是编译器问题?
如果它按照预期的方式进行,哪个规则支持它?

【问题讨论】:

    标签: c++ c++20 template-argument-deduction


    【解决方案1】:

    你又少了一对括号:

    multimap<std::string> mp = {{
        { { { "key1", "key2", "key3" }, "description1" }, "value"  },
        { { { "key4", "key5", "key6" }, "description1" }, "value2" }
    }};
    

    【讨论】:

      猜你喜欢
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 2019-09-23
      • 2014-11-22
      相关资源
      最近更新 更多