"chosen constructor is explicit in copy-initialization error" 与 clang++ 4.2



我有clang++4.2

Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn)
Target: x86_64-apple-darwin11.4.2
Thread model: posix

当我试图编译这个c++11代码时:

class ContextSummary {
    int id;
    int hops;
    std::map<std::string, int> db {};
    std::time_t timestamp;
ContextSummary(int id, const std::map<std::string, int>& db = {}, int hops = 3, std::time_t timestamp = 0)
{
    this->id = id;
    this->db = db;
    this->hops = hops;
    this->timestamp = timestamp;
}

我收到了这个错误消息。该代码适用于g++4.8

error: 
      chosen constructor is explicit in copy-initialization
  ...id, const std::map<std::string, int>& db = {}, int hops = 3, std::time_t...
                                           ^    ~~

这是叮当++错误吗?如何绕过此错误?

复制我在评论中所说的内容

这是http://cplusplus.github.io/LWG/lwg-active.html#2193。我不确定"提议的解决方案"或类似的东西是否能将其转化为C++14。在复制初始化上下文中使用显式默认构造函数的值初始化本身是否格式良好也是核心语言DRhttp://open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1518,这解释了可能存在的跨编译器差异。

如果您的实现http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1494下面的语法对于一个默认的参数来说是有效的,你可以完成

const std::map<std::string, int>& db{}

不幸的是,这是不允许的(我认为我的原因是明确地传递参数,你也不能直接初始化参数,那么为什么允许它作为默认参数呢?)。所以在我看来,唯一的方法就是显式创建

const std::map<std::string, int>& db = std::map<std::string, int>{}

决定是否要以可能更多的代码为代价来摆脱冗余。的一些替代方案

const std::map<std::string, int>& db = decltype(ContextSummary::db){}
const std::map<std::string, int>& db_ = decltype(db){}
const std::map<std::string, int>& db = std::decay<decltype(db)>::type{}

相关内容

最新更新