首页 > 解决方案 > 将一些参数绑定到模板模板参数的更简单语法

问题描述

一个类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++ 版本都可以。

标签: c++templatestemplate-templates

解决方案


如果您有一个带有两个参数的模板,您不能只指定一个参数并获得一个模板模板。那根本不可能。您也无法创建模板模板别名,因为您可以使用using. C++ 无法轻松使用模板模板,您基本上只能在完全实例化它们或将它们作为参数传递给模板时使用它们。

你也不能ExpectTTs同时使用模板模板参数和类型模板参数,因为 C++ 严格区分它们(否则你可以做一些事情,比如让ExpectTTs提取内部类型)。也许你可以让ExpectTTs只接受类型模板参数,并让A, B, 并且D有一个Inner模板,而它们本身就是类型,所以你可以让ExpectTTs总是做提取Inners 的工作。但是当然,您将无法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类型并准确返回您想要的模板模板,而不是其他替代。


推荐阅读