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;
}
#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;
}
相关文章推荐
- C++智能指针详解
- C语言之#和##
- C++ 学习笔记
- 递归分治--汉诺塔问题
- C++ 基础知识回顾(string基础、智能指针、迭代器、容器类)
- 【leetcod】Product of Array Except Self -C++
- C语言篇——指针(一)
- 关于&的思考
- C++STL之函数对象及谓词
- c++ 成员变量初始化
- 在 C/C++ 语言中特定的宏,如 __FUNCTION__
- C++用法的学习心得
- C++——运算符重载(四)
- 为什么要选择C/C++
- 收集的一些c++知识点与题目一
- c++获取系统时间(引用别人的博文)
- Effective C++学习进阶版
- ID 比较练习 C语言 文件操作 位置指针
- C语言中long long的用法
- c++中vetctor的用法