c++ - 模板化构造函数是否覆盖 C++ 中的隐式复制构造函数?

标签 c++ templates copy-constructor

模板构造函数(如下所示)是否覆盖隐式复制构造函数?

template <class T>
struct Foo
{
    T data;

    // ...

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

    // ...
};

如果是这样,如果 other 是按值而不是常量引用传递的,它是否仍然会覆盖它?

如果是这样,有没有办法在不显式定义复制构造函数的情况下解决这个问题?

最佳答案

不,那不是拷贝构造函数。标准的第 12.8 节 ([class.copy]) 要求:

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.

编译器仍将隐式生成一个默认值。

您可以通过

使它显式(需要 C++11)
Foo(const Foo<T>&) = default;

关于c++ - 模板化构造函数是否覆盖 C++ 中的隐式复制构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11016262/

相关文章:

c++ - 乘以定义的符号: mysqlclient, pthread-win32

templates - MailChimp 预览覆盖链接样式

java html 字体大小

c++ - 调用复制 ctor 和另一个 ctor

c++ - 将深拷贝构造函数添加到 std::unique_ptr<my_type>

main 中的 C++ 数组大小

c++ - 用户空间缓冲区和内存映射文件之间的 DMA

c++ - 循环依赖类中的 Typedef

C++ 赋值奇怪的行为

C++ 函数和 'identifier not found' 错误