模板化的构造函数是否覆盖C ++中的隐式复制构造函数? [英] Does a templated constructor override the implicit copy constructor in C++?

查看:131
本文介绍了模板化的构造函数是否覆盖C ++中的隐式复制构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模板化的构造函数(例如下面的)是否覆盖隐式复制构造函数?

  template< class T& 
struct Foo
{
T data;

// ...

template< class U>
Foo(const Foo< U>& other):data((T)doSomethingWith(other.data)){}

// ...
}

如果是这样,如果其他

如果是这样,有没有明确定义复制构造函数的方式?

解决方案

不,这不是一个复制构造函数。标准的第12.8节( [class.copy] )要求:


X 类的非模板构造函数是一个复制构造函数,如果它的第一个参数是 X& const X& volatile X& const volatile X& 并且没有其他参数或者所有其他参数都有默认参数。


编译器仍然会隐式生成一个默认的参数。 / p>

您可以通过

显示(需要C ++ 11)

  Foo(const Foo< T>&)= default; 


Does a templated constructor (such as the following) override the implicit copy constructor?

template <class T>
struct Foo
{
    T data;

    // ...

    template <class U>
    Foo(const Foo<U> &other) : data((T)doSomethingWith(other.data)) {}

    // ...
};

If so, does it still override it if other is passed by value rather than constant reference?

If so, is there any way around this without explicitly defining a copy constructor?

解决方案

No, that is not a copy constructor. Section 12.8 ([class.copy]) of the Standard requires that:

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.

The compiler will still implicitly generate a defaulted one.

You can make that explicit (requires C++11) by

Foo(const Foo<T>&) = default;

这篇关于模板化的构造函数是否覆盖C ++中的隐式复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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