c++ - 为什么模板参数推导不适用于此示例(来自 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)
构造函数?
解决方案
推荐阅读
- python-3.x - 我想要一种方法来“重试”错误的用户输入。有没有办法做到这一点?
- python - win32api.ShellExecute() 函数有什么作用?
- c++ - 模板参数扣除/替换失败:
- swift - 带有错误委托方法的 Swift 协议扩展仍然有效(?!)
- sql - SQL窗口函数和连接
- django - Django 错误:找不到“登录”的反向。“登录”不是有效的视图函数或模式名称
- javascript - 怎样才能在第二个小点处截数?
- php - 需要一次失败的相对路径
- flutter - 如何像这样在颤动中绘制并发自定义形状?
- git - 是否可以将子模块更改保存到主 git 索引?