【问题标题】:Anonymous temporaries and class template argument deduction - gcc vs clang匿名临时变量和类模板参数推导 - gcc vs clang
【发布时间】:2018-05-16 18:39:06
【问题描述】:

考虑以下代码sn-p:

template <typename T>
struct foo
{
    foo(T) { }
};

int main()
{
    foo{0};
}

g++ 7 愉快地创建了一个foo 类型的临时对象,推导出T = int

clang++ 5和6拒绝编译代码:

error: expected unqualified-id
    foo{0};
       ^

live example on wandbox


这是一个 clang 错误,还是标准中的某些内容阻止了 类模板参数推导 对未命名的临时对象起作用?

【问题讨论】:

    标签: c++ language-lawyer c++17 class-template template-argument-deduction


    【解决方案1】:

    Clang 错误 (#34091)

    来自[dcl.type.class.deduct]

    推导类类型的占位符也可以用在 [...] 或作为explicit type conversion (functional notation) 中的simple-type-specifier。推导类类型的占位符不应出​​现在任何其他上下文中。 [ 示例:

    template<class T> struct container {
        container(T t) {}
        template<class Iter> container(Iter beg, Iter end);
    };
    
    template<class Iter>
    container(Iter b, Iter e) -> container<typename std::iterator_traits<Iter>::value_type>;
    std::vector<double> v = { /* ... */ };
    
    container c(7);                         // OK, deduces int for T
    auto d = container(v.begin(), v.end()); // OK, deduces double for T
    container e{5, 6};                      // error, int is not an iterator
    

    — 结束示例 ]

    【讨论】:

      猜你喜欢
      • 2020-10-27
      • 2019-11-29
      • 2015-08-18
      • 2021-04-03
      • 2012-11-11
      • 1970-01-01
      • 2018-08-26
      • 1970-01-01
      相关资源
      最近更新 更多