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 小时前
C++之static_cast关键字
开发语言·c++·static_cast
奶茶树7 小时前
【C++/STL】map和multimap的使用
开发语言·c++·stl
云知谷9 小时前
【C/C++基本功】C/C++江湖风云录:void* 的江湖传说
c语言·开发语言·c++·软件工程·团队开发
ShineWinsu10 小时前
对于数据结构:堆的超详细保姆级解析—上
数据结构·c++·算法·计算机·二叉树·顺序表·
im_AMBER10 小时前
Leetcode 46
c语言·c++·笔记·学习·算法·leetcode
QX_hao10 小时前
【Go】--文件和目录的操作
开发语言·c++·golang
卡提西亚10 小时前
C++笔记-20-对象特性
开发语言·c++·笔记
三掌柜66611 小时前
C++ 零基础入门与冒泡排序深度实现
java·开发语言·c++
沐怡旸12 小时前
【穿越Effective C++】条款15:在资源管理类中提供对原始资源的访问——封装与兼容性的平衡艺术
c++·面试
利刃大大12 小时前
【高并发服务器:HTTP应用】十五、HttpRequest请求模块 && HttpResponse响应模块设计
服务器·c++·http·项目