【问题标题】:How to use a template class as a template parameter?如何使用模板类作为模板参数?
【发布时间】:2017-10-31 17:22:34
【问题描述】:

我有一个存储标量以及相关物理维度指数的类:

template <int L, int M, int T, int C, int K, int S, int I>
class Dimension<L, M, T, C, K, S, I>
{
    ...
}

我想构建一个类似于类 (Vec) 的向量,具有静态存储,用于存储这些对象的数组。 我假设 Vec 类模板看起来像:

template <Dimension<L, M, T, C, K, S, I> D, size_t N>
class Vec
{
    ...
}

但这会导致错误,因为模板参数D 取决于模板参数(LMTCKSI)。我已经通过蛮力尝试了几件事,但我只是猜测,并且希望由具有该问题的专业知识的人向其展示正确的方法。

我已经看到将template&lt;class&gt; 插入模板参数的示例,但我不太了解它实现了什么,或者即使它实际上是否适用。非常感谢您的帮助。

请注意,我知道这些类示例之前已经实现过,可能以更好的方式实现。

编辑:修正了一个错字并更改了 Vec 类的名称。

【问题讨论】:

  • 你看过std::array吗?
  • 正如我所说,我知道这种事情已经完成(例如 std::array 而不是这个向量类),但我有兴趣构建自己的。我特别希望将存储的类限制为 Dimension 类型,而不是任何类 T。

标签: c++ templates parameters template-templates


【解决方案1】:

如果我理解正确,您需要template template 参数。

不管怎样,首先记得用struct(或class)这个词来代替Dimension

template <int L, int M, int T, int C, int K, int S, int I>
struct Dimension
 { };

其次,你可以声明一个类型vect(请不要vector,它可能与标准std::vector发生冲突)如下

template <typename, std::size_t>
struct vect;

作为接收类型和无符号整数。

然后您可以如下实现部分特化(模板整数值使用std::cout exaple)

template <template <int, int, int, int, int, int, int> class Dim,
         int L, int M, int T, int C, int K, int S, int I, std::size_t N>
struct vect<Dim<L, M, T, C, K, S, I>, N>
 {
   vect ()
    { std::cout << " - L: " << L << " - M: " << M << " - T: " << T
                << " - C: " << C << " - K: " << K << " - S: " << S
                << " - I: " << I << " - N: " << N << std::endl; }
 };

你可以使用这个vect如下

vect<Dimension<2, 3, 5, 7, 11, 13, 17>, 42> v;

这也适用于 C++98。

如果您可以使用 C++11 或更高版本,则可以使用可变参数,因此可以将 vect 特化简化(稍微)如下

template <template <int...> class Dim,
         int L, int M, int T, int C, int K, int S, int I, std::size_t N>
struct vect<Dim<L, M, T, C, K, S, I>, N>
 { /* ... */ };

或者,使用可变参数,更多

template <template <int...> class Dim, int ... Is, std::size_t N>
struct vect<Dim<Is...>, N>
 { /* ... */ };

但是,在这种情况下,使用单个 Is... 值会稍微复杂一些。

但是,如果您至少可以使用 C++11,我强烈建议(按照 Miles Budnek 的示例)使用std::array

【讨论】:

  • 感谢您的解释,template template 参数现在更有意义了!
  • @Arc - 添加了一点建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-09
相关资源
最近更新 更多