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;
};
相关推荐
charlie1145141912 小时前
通用GUI编程技术——图形渲染实战(三十八)——顶点缓冲与输入布局:GPU的第一个三角形
开发语言·c++·学习·图形渲染·win32
用户805533698032 小时前
现代Qt开发教程(新手篇)1.10——进程
c++·qt
海参崴-2 小时前
C++ STL篇 AVL树的模拟实现
开发语言·c++
汉克老师2 小时前
GESP2025年6月认证C++五级( 第二部分判断题(1-10))
c++·贪心算法·分治算法·线性筛法·gesp5级·gesp五级
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 15. 三数之和 | C++ 排序+双指针
c++·算法·leetcode
vegetablesssss2 小时前
VTK切割图
c++·qt·vtk
CN-Dust3 小时前
【C++】for循环例题专题
java·c++·算法
IOT那些事儿3 小时前
Qt5 VSCode调试
c++·vscode·mingw·qt5
c++之路3 小时前
C++ 多线程
开发语言·c++
故事和你913 小时前
洛谷-算法2-3-分治与倍增5
开发语言·数据结构·c++·算法·动态规划·图论