使用模板模板参数的替代方案

Alternatives to using template template parameters

本文关键字:方案 参数      更新时间:2023-10-16

我目前使用一个具有多个参数的模板类,

template<class A, class B> class M{ };

然而,在类A的位置上,我想插入一个模板类,类似

template<class C> class A{ };

我找到的唯一解决方案是使用模板模板参数:

template< template<class C> class A, class B> class M{ };

在我的实现中,我使用的A的唯一参数化是A<B>。我不需要使用不同参数对A进行多次实例化,例如,我不需要在M中实例化A<int>A<double>A<long double>

是否有模板模板参数的替代方案?我问的原因是这个帖子的后续内容,在他的回答中@Evan Teran说他只使用过一次模板参数。。。

我想我的问题有一个转折点:使用模板-模板参数有缺点吗?

假设B可以从A<B>中以某种方式确定,那么您只需要使用一个模板参数:

template <class A> class M
{
  typedef typename A::The_B_Type B;
};

当然,The_B_Type必须是A<B>中的有效typedef。这就是标准库容器提供所有typedef的原因之一。例如,如果模板Astd::vector,则可以执行以下操作:

template <class A> class M
{
  typedef typename A::value_type B;
};

您可以将实例化的A<B>作为参数,然后使用traits类提取传递给A<B>B(如果需要):

template<typename T>
struct extract_b {}; // SFINAE enabled
template<template<class>class A, typename B>
struct extract_b< A<B> > {
  typedef B type;
};
// C++11, you can replace it with typename extract_b<T>::type at point of use
// if you lack support for it:
template <typename T>
using ExtractB = typename extract_b<T>::type;
template<typename A>
struct M {
  typedef ExtractB<A> B;
  // ...
};

traits类的名称不好,但您可以看到,我可以从A<B>中获得template参数,并在M<A>中公开它。