7

考虑以下代码片段:

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};
       ^

wandbox 上的实时示例


这是一个铿锵的错误,还是标准中的某些东西阻止了类模板参数推导用于未命名的临时对象?

4

1 回答 1

8

Clang 错误 ( #34091 )

来自[dcl.type.class.deduct]

推导类类型的占位符也可以在 [...] 中使用,或者在显式类型转换(功能符号)中用作简单类型说明符。推导类类型的占位符不应出​​现在任何其他上下文中。 [ 例子:

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

—结束示例]

于 2017-12-03T03:39:12.463 回答