C++11右值引用、完美转发foward、可变模板参数实例

3 篇文章 0 订阅
#include <iostream>
using namespace std;


struct A{
    int x;
    A(int _x):x(_x){
        cout<<"A constructor, x="<<x<<endl;
    }
    A(const A& a):x(a.x){
        cout<<"A copy constructor, x="<<x<<endl;
    }
};

struct B{
    int x;
    double y;
    B(int _x,double _y):x(_x),y(_y){
        cout<<"B constructor, x="<<x<<", y="<<y<<endl;
    }
    B(const A& a):x(a.x),y(8.8){
        cout<<"B constructor X A, x="<<x<<", y="<<y<<endl;
    }
    B(const B& a):x(a.x),y(a.y){
        cout<<"B copy constructor, x="<<x<<", y="<<y<<endl;
    }
};

template <typename T,typename... Args>
T* Instance1(Args... args)
{
    return new T(args...);
}

template <typename T,typename... Args>
T* Instance2(Args&&... args)
{
    return new T(std::forward<Args>(args)...);
}

void test(){
    cout<<"------------"<<endl;
    A *a=Instance1<A>(1);
    delete a;
    cout<<"------------"<<endl;
    A t(2);
    a=Instance1<A>(t);
    delete a;
    cout<<"------------"<<endl;
    a=Instance2<A>(t);
    delete a;
    cout<<"------------"<<endl;
    cout<<"------------"<<endl;
    B *b=Instance1<B>(1,2.3);
    delete b;
    cout<<"------------"<<endl;
    b=Instance1<B>(t);
    delete b;
    cout<<"------------"<<endl;
    b=Instance2<B>(t);
    delete b;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值