【问题标题】:How does the object creation work for this class template?此类模板的对象创建如何工作?
【发布时间】:2019-09-25 18:10:28
【问题描述】:

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

#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&lt;char&gt; a('A', 'A'); 的第一种情况那样创建显式对象?我没有看到使用g++ -Wall -Wextra --std=c++11 编译的编译错误。此外,如果 cppreference 中解释此行为的特定子句将不胜感激,因为我错过了确定解释这种行为的位置。

【问题讨论】:

  • 我不能告诉你为什么他们不给对象名称,但由于他们没有这样做,所以创建了一个临时对象,在声明后在 ; 处销毁。
  • @NathanOliver:这是官方记录的还是特定于编译器的?已知此类临时对象会在其他地方使用吗?
  • 由于C++标准的不同部分,需要所有编译器都支持。这是经常发生的事情。假设您有一个函数采用您不关心的A。无需创建 A 对象并为其命名,您只需执行 function(A&lt;char, char&gt;('A', 'A'));

标签: c++ template-instantiation


【解决方案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 做其他事情,则需要通过名称来引用它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2014-06-11
    • 2012-05-10
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多