首页 > 解决方案 > 为什么模板参数推导不适用于此示例(来自 A Tour of C++,6.2.3 模板参数推导)?

问题描述

下面的例子是从 A Tour of C++ (6.2.3 Template Argument Deduction) 一书中复制而来的。

template<typename T>
class Vector {
public:
    Vector(int);
    Vector(initializer_list<T>); //initializer-list constructor
    //...
};
Vector<int> v3(1); //here we need to be explicit about the element type (no element type is mentioned)

如果Vector v3(1)改为使用,则会出现以下编译错误(MSVC2019,使用 /std:c++latest):

 - E0289: no instance of constructor "Vector" matches the argument list.
 - C2641: cannot deduce template arguments for 'Vector'.
 - C2783: 'Vector<T> Vector(int)': could not deduce template arguments for 'T'
 - C2784: 'Vector<T> Vector(Vector<T>)': could not deduce template arguments for 'Vector<T>' from 'int'.
 - ...

我不明白为什么这no element type is mentioned部分在这里是相关的。如果你写auto i(1);,也没有提到元素类型,但i类型设置为int。为什么Vector v3(1);编译器也不能使用Vector(int)构造函数?

标签: c++templatesc++20

解决方案


推荐阅读