1. 程式人生 > >C++11右值引用、完美轉發foward、可變模板引數例項

C++11右值引用、完美轉發foward、可變模板引數例項

#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;

}