c++ - 以某种方式“使用”类型列表(在 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 的类,其中他以某种方式指定了类型列表。稍后,我需要处理该列表。他如何指定它仍然是开放的。所以寻找一种简单的方法来做到这一点。不需要可以在此处某处找到的过于复杂的“在编译时连接类型列表”模式。
解决方案
一种可能的替代方法是定义一种类型包装器(因为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
但没有实例化引用的类型。
推荐阅读
- javascript - Selection modify by sentence 选择2个句子
- azure - 如何在语言生成模板中使用动态值?
- python - 无法使用请求从网页的不同容器中捕获某个字段
- javascript - Vue 3 组合 API 单元测试:$route 在 onMounted() 钩子中未定义
- spring - Azure AD 身份验证与 WebApplication 访问访问另一个资源服务器的资源服务器
- angular - “typeof Observable”类型上不存在“of”属性。& return Observable.of(null);
- node.js - 在 React-Nodejs 项目中没有从 API 获得有效响应
- swift - 如何解决两个 Pod 之间的 Objective-C 兼容性标头冲突?
- javascript - 从过滤深度嵌套的对象数组中返回新对象
- python - Pandas:根据不同的日期时间段加入数据框