栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Java

C++ 11 模板改进

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 11 模板改进

模板

目录

模板

右尖括号

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

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

在C++11之后,加入了新的表示方 法,允许任意个数、任意类别的模板参数,同时也不需要在定义时将参数的个数固定。

参数包

template 
void printf(const std::string &str, Args... args);

其中,Args 与 args 分别代表模板与函数的变长参数集合, 称之为参数包 (parameter pack)。参数包必须要和运算符"…"搭配使用。

sizeof 参数包

template
void magic(Ts... args) 
{
	std::cout << sizeof...(args) << std::endl;
}

How

递归解包

template 
void fun(const T& t){
	cout << t << 'n';
}
 
template 
void fun(const T& t, Args ... args){
	cout << t << ',';
	fun(args...);//递归解决,利用模板推导机制,每次取出第一个,缩短参数包的大小。
}

fold expression

template 
void DummyWrapper(T... t){}
 
template 
T unpacker(const T& t){
	cout<<','<
void write_line(const T& t, const Args& ... data){
    cout<<','<外置递归

template 
void _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
template 
void 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)...);
}

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1040519.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号