我有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...

                                           ^    ~~


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

最佳答案

复制我在评论中说的话


这是http://cplusplus.github.io/LWG/lwg-active.html#2193。我不确定“建议的分辨率”或等同的方法是否使它成为C ++ 14。是否在复制初始化上下文中使用显式默认构造函数进行值初始化本身是否格式正确,这本身也是核心语言DR http://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{}

10-07 19:45
查看更多