c++ - 匿名临时对象和类模板参数推导 - gcc vs clang

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

考虑以下代码片段:

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 错误,还是标准中有什么东西阻止类模板参数推导为未命名的临时对象启动?

最佳答案

Clang 错误 ( #34091 )

来自 [dcl.type.class.deduct] :

A placeholder for a deduced class type can also be used in [...] or as the simple-type-specifier in an explicit type conversion (functional notation). A placeholder for a deduced class type shall not appear in any other context. [ Example:

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

— end example ]

关于c++ - 匿名临时对象和类模板参数推导 - gcc vs clang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614027/

相关文章:

c++ - 非成员函数需要通过指针打印出一个数组

c++ - 返回通过引用分配的引用局部变量

c++ - 我想获得一组唯一的 n*n 数组,这些数组在 C++ 中的随机位置仅包含 0 或 1

c++ - set::vector 初始化用数字引号

c++ - 使用强类型枚举的模板参数推导

c++ - 创建多线程

c++ - 如何避免在const自动对象曾经使用的存储中创建任何对象?

不寻常架构的 C 指针算法

c++ - 对迭代器的钳制是否有效

c++ - 统一的调用语法和函数指针