具有可变通用引用和复制构造函数的c ++ 11构造函数 [英] c++11 constructor with variadic universal references and copy constructor

查看:88
本文介绍了具有可变通用引用和复制构造函数的c ++ 11构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们也有带有通用引用参数的构造函数,那么如何声明副本构造函数?

How to declare copy constructor, if we have constructor with universal reference arguments, also?

http://coliru.stacked-crooked.com/a/4e0355d60297db57

struct Record{
    template<class ...Refs>
    explicit Record(Refs&&... refs){
        cout << "param ctr" << endl;
    }

    Record(const Record& other){     // never called
        cout << "copy ctr" << endl;
    }

    Record(Record&& other){         // never called
        cout << "move ctr" << endl;
    }    
};

int main() {
    Record rec("Hello");    
    Record rec2(rec);  // do "param ctr"

    return 0;
}

根据 std :: tuple的此构造函数列表 http://en.cppreference.com/w / cpp / utility / tuple / tuple [看案例3和8]这个问题在标准库中以某种方式解决了...但是我无法通过stl的代码来解决。

According to this constructor list of std::tuple http://en.cppreference.com/w/cpp/utility/tuple/tuple [look case 3 and 8] this problem somehow solved in standard library... But I can't get through stl's code.

PS问题与构造函数中的C ++通用引用和返回值优化(rvo)

PPS现在,我只是为真正的EXPLICIT调用添加了其他第一个参数 Record(call_constructor,Refs& ... refs)。而且我可以手动检测是否只有一个参数,是否为 Record ,然后重定向调用以复制ctr / param ctr,但是....相信没有标准的方法...

P.P.S. For now, I just added additional first param Record(call_constructor, Refs&&... refs) for really EXPLICIT call. And I can manually detect if we have only one param and if it is Record, and than redirect call to copy ctr/param ctr, but.... I can't believe there is no standard way for this...

推荐答案

在您的示例中,转发引用与<$ c $一起使用c> Record& 。

In your example, the forwarding reference is used with Record&.

因此,您可以为 Record& 添加额外的重载(转发给复制构造函数):

So you may add an extra overload for Record& (to forward to copy constructor):

Record(Record& other) : Record(static_cast<const Record&>(other)) {}

或在具有转发参考的那一个上使用sfinae。

or use sfinae on the one with forwarding reference.

这篇关于具有可变通用引用和复制构造函数的c ++ 11构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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