0

我在下面有这段代码,我正在尝试我正在学习的课程,这几乎可以做到预期做的事情

#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 中解释此行为的特定子句将不胜感激,因为我错过了确定在哪里解释了这种行为。

4

1 回答 1

1
// 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');

请注意,您可以将名称 b、c 和 d 或任何其他有效标识符指定给其他 A,但仍会看到相同的结果;或者,由于a在其定义后未使用命名的名称,因此您也可以删除该名称,并将其作为对构造函数的调用,该构造函数不会像其他名称那样绑定到名称。无论如何,这个特定程序的结果相同,尽管如果您在构建后想要做其他事情a, b, c or d,则需要通过名称引用它们。

于 2019-09-25T20:20:45.840 回答