首页 > 解决方案 > 以某种方式“使用”类型列表(在 C++17 及更高版本中)

问题描述

如何使以下简单的想法起作用?

template <typename ...Types>
void Function()
{ /* do something that depends on the Types */ }

void Test()
{

    using my_types = { int, float };    // not possible
    using my_types = int, float;        // alternative disallowed syntax
    Function<my_types>();
    
    Function<int,float>();              // OK, but I can't specify manually

}

为什么不直接支持这种类型的列表?什么是简单的解决方法?

笔记

为了阐明用例:用户定义了一个类似 Trait 的类,其中他以某种方式指定了类型列表。稍后,我需要处理该列表。他如何指定它仍然是开放的。所以寻找一种简单的方法来做到这一点。不需要可以在此处某处找到的过于复杂的“在编译时连接类型列表”模式。

标签: c++templatestypesvariadic-templates

解决方案


一种可能的替代方法是定义一种类型包装器(因为std::tuple它完全不使用模板参数)

template <typename...>
struct type_wrapper
 { };

并声明Function()接收该类型的对象

template <typename ...Types>
void Function (type_wrapper<Types...> const &)
{ /* do something that depends on the Types */ }

因此您可以将所需包装器的对象传递给Function()并让模板推导工作

using my_wrapped_types = type_wrapper<int, float>;

Function(my_wrapped_types{}); 

为什么不直接支持这种类型的列表?什么是简单的解决方法?

因为std::tuple它涵盖了大多数用例,并且如您所见,当您想要更轻的东西时编写包装器是微不足道的。

我不想将这些类型的对象传递给函数。

这样,您传递了一个类型的对象,type_wrapper但没有实例化引用的类型。


推荐阅读