C++遍历TypeList(可变模板参数)的简单办法

搬砖的小菜鸡 / 2023-08-21 / 原文

       这里例举了两种方案,一种是基于C++ 17的constexpr,实现起来更精简。另外一种使用传统的方式,C++ 11就可以用了。

       另外C++11的方案也是一种计算不定参数模板参数个数的方法。

#include <iostream>
#include <string>

// in C++ 17
#if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L)
template <typename T, typename... ParamTypes>
void printTypes()
{
    std::cout << typeid(T).name() << std::endl;

    if constexpr (sizeof...(ParamTypes) > 0)
    {
        printTypes<ParamTypes...>();
    }
}
#else
// in C++ 11
template <typename T, typename... ParamTypes>
struct TPrintVariadicTemplateTypes
{
    enum 
    {
        Count = TPrintVariadicTemplateTypes<ParamTypes...>::Count + 1
    };

    void operator ()()
    {
        std::cout << typeid(T).name() << std::endl;

        TPrintVariadicTemplateTypes<ParamTypes...>()();
    }
};

template <typename T>
struct TPrintVariadicTemplateTypes<T>
{
    enum 
    {
        Count = 1
    };

	void operator ()()
	{
		std::cout << typeid(T).name() << std::endl;
	}
};

template <typename... ParamTypes>
void printTypes()
{
	TPrintVariadicTemplateTypes<ParamTypes...>()();
}

#endif

int main()
{
     printTypes<int>();
     printTypes<int, float, std::string>();
}