我有下面的代码,这是我正在尝试的课程中尝试的,几乎可以完成预期的工作
#include <iostream>
template <typename T, class U = int>
class A {
public:
T x;
U y;
A(T x, U y) { std::cout << x << " " << y << std::endl; }
};
int main() {
A<char> a('A', 'A');
A<char, int>('A', 65);
A<char, char>('A', 'A');
return 0;
}
但是我不明白下面的部分是如何工作的。我了解模板的默认参数部分如何工作,但不了解模板类实例化后代码如何创建对象。
A<char, int>('A', 65);
A<char, char>('A', 'A');
为什么不像A<char> a('A', 'A');
的第一种情况那样创建显式对象?我没有看到使用g++ -Wall -Wextra --std=c++11
进行编译的编译错误。另外,如果cppreference中的一个特定子句能够解释这种行为,那么我将不胜感激,因为我错过了确定这种行为的解释位置。
// Explicit instantiation of A<char, int>.
// The result of the constructor call A(char x, int y) is not used, i.e.
// is not bound to a name as in A<char> a('A', 'A'); however, because the
// constructor has a side effect of calling std::cout, we can still tell that
// it ran.
A<char, int>('A', 65);
// Explicit instantiation of A<char, char> that is not bound to a name.
A<char, char>('A', 'A');
注意,您可以给其他A赋予名称b,c和d或任何其他有效标识符,但仍然看到相同的结果;或者,由于在定义后未使用名称为a
的名称,因此您也可以删除该名称,而只是将其作为未绑定到其他名称的构造函数的调用。相同的结果对于此特定程序,尽管,即使在构造后稍后您想要对
a, b, c or d
进行其他处理,也需要使用名称进行引用。