您的位置:首页 > 编程语言 > C语言/C++

C++11 变长模版和完美转发实例代码

2015-09-09 17:56 513 查看
C++11 变长模版和完美转发实例代码

#include <memory>
#include <iostream>
#include <vector>
#include <stdarg.h>
using namespace std;

struct A
{
A()
{
}
A(const A& a)
{
cout << "Copy Constructed " << __func__ << endl;
}
A(A&& a)
{
cout << "Move Constructed " << __func__ << endl;
}
};

struct B
{
B()
{
}
B(const B& b)
{
cout << "Copy Constructed " << __func__ << endl;
}
B(B&& b)
{
cout << "Move Constructed " << __func__ << endl;
}
};

//变长模版定义
template<typename ... T> struct MultiTypes;
template<typename T1, typename ... T>
struct MultiTypes<T1, T...> : public MultiTypes<T...>
{
T1 t1;
MultiTypes<T1, T...>(T1 a, T ... b)
: t1(a), MultiTypes<T...>(b...)
{
cout << "MultiTypes<T1, T...>(T1 a, T ... b)" << endl;
}
};
template<> struct MultiTypes<>
{
MultiTypes<>()
{
cout << "MultiTypes<>()" << endl;
}
};
//完美装发
template<template<typename ... >class VariadicType,typename... Args>
VariadicType<Args...> Build(Args&&... args)
{
return VariadicType<Args...>(std::forward<Args>(args)...);
}
int main()
{
A a;
B b;
Build<MultiTypes>(a, b);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: