模板
目录
模板
右尖括号
Abstract
模板的别名
Abstract
Demo
函数模板的默认模板参数
Abstract
Demo
变长参数模板
Abstract
How
Demo
右尖括号
Abstract
C++11之前是不允许两个右尖括号出现的,会被认为是右移操作符,所以需要中间加个空格进行分割,避免发生编译错误。
模板的别名
Abstract
C++11引入了using,可以轻松的定义别名,而不是使用繁琐的typedef。
Demo
typedef std::vector> vvi; // before c++11
using vvi = std::vector>; // c++11
template
struct Alloc { };
template
using Vec = vector>; // 类型标识为 vector>
Vec v; // Vec 同 vector>
函数模板的默认模板参数
Abstract
Abstract
C++11之前只有类模板支持默认模板参数,函数模板是不支持默认模板参数的,C++11后都支持。
类模板的默认模板参数必须从右往左定义,而函数模板则没有这个限制。
对于函数模板,参数的填充顺序是从左到右的,而通常情况下c/c++默认入栈方式:__cdel,也就是以右到左将参数压入堆栈
Demo
template
class A {
T value;
};
template // error
class A {
T value;
};
emplate
R func1(U val) {
return val;
}
template
R func2(U val) {
return val;
}
int main() {
cout << func1(99.9) << endl; // 99
cout << func1(99.9) << endl; // 99.9
cout << func1(99.9) << endl; // 99.9
cout << func1(99.9) << endl; // 99
cout << func2(99.9) << endl; // 99
cout << func1(99.9) << endl; // 99.9
cout << func2(99.9) << endl; // 99.9
cout << func2(99.9) << endl; // 99
return 0;
}
变长参数模板
Abstract
Abstract
在C++11之后,加入了新的表示方 法,允许任意个数、任意类别的模板参数,同时也不需要在定义时将参数的个数固定。
参数包
templatevoid printf(const std::string &str, Args... args);
其中,Args 与 args 分别代表模板与函数的变长参数集合, 称之为参数包 (parameter pack)。参数包必须要和运算符"…"搭配使用。
sizeof 参数包
templatevoid magic(Ts... args) { std::cout << sizeof...(args) << std::endl; }
How
递归解包
templatevoid fun(const T& t){ cout << t << 'n'; } template void fun(const T& t, Args ... args){ cout << t << ','; fun(args...);//递归解决,利用模板推导机制,每次取出第一个,缩短参数包的大小。 }
fold expression
templatevoid DummyWrapper(T... t){} template T unpacker(const T& t){ cout<<','< void write_line(const T& t, const Args& ... data){ cout<<','< 外置递归 templatevoid _write(const T& t){ cout << t << 'n'; } template void _write(const T& t, Args ... args){ cout << t << ','; _write(args...);//递归解决,利用模板推导机制,每次取出第一个,缩短参数包的大小。 } template inline void write_line(const T& t, const Args& ... data){ _write(t, data...); } Demo
templatevoid unpack(T&& t) { std::cout << std::forward (t) << ' '; } template void debugLogImpl(Args&& ... args) { int dummy[] = {0 , (unpack(std::forward(args)), 0)...}; MOOS_UNUSE(dummy); std::cout << 'n'; } template void debugLog(Args&& ... args) { debugLogImpl(std::forward(args)...); }