代码之家  ›  专栏  ›  技术社区  ›  asmmo

decltype()不适用于正在编译的类模板

  •  1
  • asmmo  · 技术社区  · 5 年前

    下面的代码片段有问题。 values 在编译之前不会知道。对吗?

    vector values{1, 2, 3, 4, 5, 6};
    vector<decltype(values[0])> {values};
    ostream_iterator<int> printer{cout," "};
    copy(ints.crbegin(),ints.crend(),printer);
    
    1 回复  |  直到 5 年前
        1
  •  4
  •   Indiana Kernick Michael Durrant    5 年前

    问题是 values[0] 是一个 int & . 你自己看看:

    static_assert(std::is_same_v<decltype(values[0]), int &>);
    

    创建一个引用向量是完全错误的。要解决这个问题,只要使用 decltype

    std::vector values{1, 2, 3, 4, 5, 6};
    decltype(values) ints(values.cbegin(), values.cend());
    

    以你的例子来说,这些都不是必需的,因为你只是在复制一个向量。所以你可以这样做:

    std::vector ints = values;
    // Or avoid CTAD entirely
    auto ints = values;