相关疑难解决方法(0)

模板类上的c ++模板复制构造函数

我有一个模板类,它有一个模板复制构造函数.问题是当我使用具有相同模板类型的此类的另一个实例来实例化此类时,我的模板复制构造函数未被调用.为什么不匹配?这是代码片段:

#include <iostream>

template <typename T>
class MyTemplateClass
{
    public:
        MyTemplateClass()
        {
            std::cout << "default constructor" << std::endl;
        }

        /*
        MyTemplateClass(const MyTemplateClass<T>& other)
        {
            std::cout << "copy constructor" << std::endl;
        }
        */

        template <typename U>
        MyTemplateClass(const MyTemplateClass<U>& other)
        {
            std::cout << "template copy constructor" << std::endl;
        }
};

int main()
{
    MyTemplateClass<int> instance;
    MyTemplateClass<int> instance2(instance);
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

输出是

default constructor
Run Code Online (Sandbox Code Playgroud)

但是如果我显式地编写默认的复制构造函数(通过取消注释它),那么输出就变成了

default constructor
copy constructor
Run Code Online (Sandbox Code Playgroud)

我真的不明白.我用我的本地编译器(clang-500.2.79)和这个(gcc 4.9.2)测试了它并得到了相同的结果.

c++ templates copy-constructor

9
推荐指数
1
解决办法
4823
查看次数

模板“复制构造函数”不会阻止编译器生成的移动构造函数

考虑以下程序及其中的注释:

template<class T>
struct S_ {
    S_() = default;

    // The template version does not forbid the compiler
    // to generate the move constructor implicitly
    template<class U> S_(const S_<U>&) = delete;

    // If I make the "real" copy constructor
    // user-defined (by deleting it), then the move
    // constructor is NOT implicitly generated
    // S_(const S_&) = delete;
};

using S = S_<int>;

int main() {
    S s;
    S x{static_cast<S&&>(s)};
}
Run Code Online (Sandbox Code Playgroud)

问题是:为什么用户自定义模板构造函数(当U = T时有效地充当副本构造函数)阻止了编译器生成move构造函数,相反,如果我定义了“真实”副本,构造函数(通过删除它),那么move构造函数不是隐式生成的(程序无法编译)吗?(可能的原因是,当T = U?时,“模板版本”也不遵守复制构造函数的标准定义。) …

c++ c++11

1
推荐指数
1
解决办法
418
查看次数

标签 统计

c++ ×2

c++11 ×1

copy-constructor ×1

templates ×1