C++ 模板参数展开

C++ 模板参数展开


一、获取可变参数大小

背景:

FLen<int, char, long> Len;

我想要获取模板参数类型的总大小

cpp 复制代码
template<typename T,typename ...ParamTypes>
class FLen
{
public:
	enum
	{
		Number = FLen<T>::Number + FLen<ParamTypes...>::Number
	};
};

template<typename Last>
class FLen<Last>
{
public:
	enum
	{
		Number = sizeof(Last)
	};
};

思想还是类似递归调用的思想,只是递归的不是函数而是模板

cpp 复制代码
int main()
{
	FLen<int, char, long> Len;

	std::cout << Len.Number << std::endl;

	system("pause");
	return 0;
}

二、通过模版循环继承的方式来展开可变参数

最终目的是构建一个 TestIndex 类型,其模板参数是从0开始到N-1的整数序列。

cpp 复制代码
template<int...>
struct TestIndex
{

};

template<int N,int...ParamTypes>
struct FSpawnIndex : FSpawnIndex<N - 1,N - 1,ParamTypes...>
{

};

template<int...ParamTypes>
struct FSpawnIndex<0,ParamTypes...>
{
	typedef TestIndex<ParamTypes...> Type;
};

解释一下原理和流程

起始:FSpawnIndex<3>(此时 N=3,参数包为空)

继承:FSpawnIndex<3> : FSpawnIndex<2,2>

在内部,参数包变为 2

下一步:FSpawnIndex<2,2> : FSpawnIndex<1,1,2>

参数包变为 1,2(注意:每次递归在参数包头部添加)

下一步:FSpawnIndex<1,1,2> : FSpawnIndex<0,0,1,2>

参数包变为 0,1,2

匹配终止条件:FSpawnIndex<0,0,1,2>

定义 Type 为 TestIndex<0,1,2>

cpp 复制代码
int main()
{
	using TestType = FSpawnIndex<3>::Type;

	std::cout << typeid(TestType).name() << std::endl;

	system("pause");
	return 0;
}

三、改用Using去实现循环继承

cpp 复制代码
template<int...>
struct TestIndex
{

};

template<int N,int...ParamTypes>
struct FSpawnIndex
{
	using Type = typename FSpawnIndex<N - 1, N - 1, ParamTypes...>::Type;
	//          ↑↑↑↑↑
	// 这个 typename 必不可少!
};

template<int...ParamTypes>
struct FSpawnIndex<0, ParamTypes...>
{
	typedef TestIndex<ParamTypes...> Type;
};

在 C++ 模板元编程中,typename 关键字在这里起着​​关键作用​​,主要用于解决​​依赖名称的解析问题​​。

cpp 复制代码
int main()
{
	using TestType = FSpawnIndex<3>::Type;

	std::cout << typeid(TestType).name() << std::endl;

	system("pause");
	return 0;
}

​​什么是依赖名称?​​

FSpawnIndex<N-1, ...>::Type 是​​依赖于模板参数 N 和 ParamTypes... 的名称​​

编译器在解析模板时,无法确定 ::Type 是什么(可能是类型、静态成员或嵌套模板)

例如以下例子

cpp 复制代码
// 情况分析:
struct FSpawnIndex</*...*/> {
    // 可能1:Type 是类型(typedef/using)
    typedef ... Type;

    // 可能2:Type 是静态成员
    static int Type;

    // 可能3:Type 是嵌套模板
    template<...> class Type;
};
相关推荐
我不会插花弄玉7 小时前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
郝学胜-神的一滴9 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
西西弗Sisyphus10 小时前
C++ explicit 关键字工程实践
开发语言·c++
AIgorithmGEEK13 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
一拳一个呆瓜15 小时前
【STL】头文件:<cmath>
c++·stl
草莓熊Lotso15 小时前
【C++ 基于微服务的即时通讯系统】ElasticSearch 用户数据管理实现
linux·数据库·c++·elasticsearch·微服务·架构
慧都产品智能化16 小时前
Qt 开发 CAD/CAM 工序表的隐性成本分析
c++·qt·qt5·qt6.3
eggwyw17 小时前
linux下的C\C++多进程多线程编程实例详解
开发语言·c++
青少儿编程课堂18 小时前
第十八届蓝桥杯青少组图形化真题 + 全国青少年信息素养大赛 + 电子学会图形化考级:校园泡泡堂大挑战解析
c++·python·算法·bfs·信息学竞赛
小七在进步19 小时前
string的实现(3)
开发语言·c++·笔记·visual studio