标准为何不将模板构造函数视为副本构造函数? [英] Why doesn't the standard consider a template constructor as a copy constructor?

查看:62
本文介绍了标准为何不将模板构造函数视为副本构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是复制构造函数的定义, [class.copy.ctor/1] :

Here's the definition of copy constructor, [class.copy.ctor/1]:

如果类X的第一个参数的类型为X& ;、 const X& ;、 volatile X&类型,则它是副本构造器.或const volatile X& ;,或者没有其他参数,或者所有其他参数都有默认参数([dcl.fct.default]).

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments ([dcl.fct.default]).

为什么标准不将模板作为复制构造函数?

Why does the standard exclude templates as copy constructors?

在这个简单的示例中,两个构造函数都是副本构造函数:

In this simple example, both constructors are copy constructors:

struct Foo {
    Foo(const Foo &); // copy constructor
    Foo(Foo &);       // copy constructor
};

请参阅以下类似示例:

struct Foo {
     Foo() = default;

     template <typename T>
     Foo(T &) {
         printf("here\n");
     }
};

int main() {
    Foo a;
    Foo b = a;
}

在此示例中,将在此处进行打印.因此,看来我的模板构造函数是一个复制构造函数,至少它的行为类似于一个(在通常调用复制构造函数的上下文中被调用).

In this example, here will be printed. So it seems that my template constructor is a copy constructor, at least it behaves like one (it is called in a context where copy constructors are usually called).

为什么文本中存在非模板"要求?

Why is the "non-template" requirement there in the text?

推荐答案

让我们将模板放置一秒钟.如果一个类未声明副本构造函数,则将生成一个隐式默认的构造函数.可以将其定义为已删除,但是仍然是默认设置.

Let's put templates aside for a second. If a class doesn't declare a copy constructor, an implicitly defaulted one is generated. It may be defined as deleted, but it's defaulted nonetheless.

成员模板不是成员函数.仅在需要时才从中实例化成员.

A member template is not a member function. Members are instantiated from it only when needed.

那么,编译器如何仅从类定义中知道是否需要使用 T = Foo 进行专门化?不可以但这正是需要决定如何处理对隐式默认副本构造函数(AND move构造函数)的潜在需求的基础.变得混乱了.

So how can a compiler know from the class definition alone whether or not a specialization with T = Foo will ever be needed? It can't. But it's exactly that on which it needs to base a decision of how to handle a potential need for an implicitly defaulted copy constructor (AND move constructor). That becomes messy.

最简单的方法是排除模板.无论如何,我们总会有一些拷贝构造函数,它默认会做正确的事情 TM ,并且由于它不是从模板中实例化的,因此将受到重载解析的青睐.

The easiest approach is to exclude templates. We'll always have some copy constructor anyway, it will do the correct thingTM by default, and will be favored by overload resolution because it's not instantiated from a template.

这篇关于标准为何不将模板构造函数视为副本构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆