c++ - 将一些参数绑定到模板模板参数的更简单语法
问题描述
一个类ExpectTTs
接受许多模板模板参数:
template< template<typename> class... TT >
struct ExpectTTs {};
另一种类型需要两个模板参数。我需要修复一个并将其余的传递给ExpectTTs
.
目前我正在使用这个解决方案:
template< typename T >
struct TwoTs {
template< typename U >
struct Inner {};
};
ExpectTTs< TwoTs<int>::Inner >
是否可以更改某些内容以便我可以传递一个简单的模板实例TwoTs<int>
化ExpectTTs
?
在我的代码库中的几个点中,我有类似的表达式ExpectTTs< A, B, C<int>::Inner, D, E<int,int>::Inner, F<void>::Inner >
,而且似乎没有必要难以读写。
任何 C++ 版本都可以。
解决方案
如果您有一个带有两个参数的模板,您不能只指定一个参数并获得一个模板模板。那根本不可能。您也无法创建模板模板别名,因为您可以使用using
. C++ 无法轻松使用模板模板,您基本上只能在完全实例化它们或将它们作为参数传递给模板时使用它们。
你也不能ExpectTTs
同时使用模板模板参数和类型模板参数,因为 C++ 严格区分它们(否则你可以做一些事情,比如让ExpectTTs
提取内部类型)。也许你可以让ExpectTTs
只接受类型模板参数,并让A
, B
, 并且D
有一个Inner
模板,而它们本身就是类型,所以你可以让ExpectTTs
总是做提取Inner
s 的工作。但是当然,您将无法std::optional
直接传递 STL 模板。
你可以(在我看来)在你的设计中改进的一件小事是使用这样的东西:
#include <utility> // For the example
#include <optional>
template<template<class> class...>
struct ExpectTTs {};
template<template<class...> class TT, class T>
struct bind {
template<class U>
using bound_t = TT<T, U>;
};
ExpectTTs<std::optional, bind<std::pair, int>::bound_t> e{};
它可能更冗长,但它不需要侵入式Inner
类型并准确返回您想要的模板模板,而不是其他替代。
推荐阅读
- javascript - 如何用按钮修改“oninput”?
- c++ - Qt 中的专辑封面艺术
- java - ResponseEntityExceptionHandler 为 401 异常返回空响应正文
- javascript - 如何自动调整文本区域的大小
- java-native-interface - 将值从方法解析到另一个方法JNI(C++)
- plugins - Lua 中用于处理 JWT 的自定义 Kong 插件
- vb.net - 为经过 Azure AD 身份验证的 Web 应用程序获取 OAuth 持有者令牌的简单过程是什么?
- r - 使用 ggplot 和 gtable 对齐多个图
- vuejs2 - Vue CSS 模块
- php - 在函数php中不使用类的原因是什么