【问题标题】:Specialization of a template class (array as input for the constructor)?模板类的特化(数组作为构造函数的输入)?
【发布时间】:2015-06-06 06:10:39
【问题描述】:

假设我有一个模板类:

template <typename T>
class TC
{
...
};

还有两个普通类:

class A
{
...
};

class B : public A
{
...
}

我可以显式实例化

TC<std::string> a(someString);
TC<int> a(5);
TC<A> a(someTestClassA);
TC<B> a(someTestClassB); 

我想专门化模板类,以便它可以接受动态数组作为构造函数输入:

TC<int[]> a(new int[5]);
TC<int[]> b(a);
TC<B[]> c(new B[5]);

如何在构造函数中“读取”数组的大小?

专业化(我认为)如下:

template <typename T>
class TC<T []>
{
    public:
    TC() : ptr(new T[n]) { }

    T * ptr;
};

如何找出数字n?

编辑:

数字 n 在 main 函数中明确说明(因此,main 在编译时知道数字,但我如何告诉 TC[] 构造函数 n 是什么?)。
示例:

TC<int[]> a(new int[5]); // in the TC[] class constructor, n should be 5

我认为我正在寻找以下的类比(但对于类,即构造函数):

template <typename T, size_t N> 
void f( T (&a)[N])
{
    for(size_t i=0; i != N; ++i) a[i]=0;
}

【问题讨论】:

  • 您无法读取传递数组的长度/大小。不在模板中,也不在任何其他构造中。将其作为另一个变量传递给函数(在本例中为构造函数)
  • 在这一行:TC a(new int[5]); , n 等于 5 并且在编译时已知,即我在源代码中明确说明了这个数字
  • new int[5] 的类型是int*。无法从该表达式中恢复维度 5。
  • @AltairAC "数字 n 已在 main 函数中明确说明" 您仍然需要对 int[5] 进行专门化(因此基本上适用于所有可能的大小),其实和int[]不一样。

标签: c++ arrays


【解决方案1】:

“如何找出数字 n?”

你不能。

请改用std::array&lt;&gt;(或std::vector&lt;&gt;,如果您在编译时不知道实际大小),它们旨在解决这类问题。


相关问答:Can someone explain this template code that gives me the size of an array?

您可能仍然不想自己实现它,这可能很难在专业化中使用。

【讨论】:

    【解决方案2】:

    您可以部分专注于已知大小的原始数组:

    template <typename T, size_t N>
    class TC<T[N]>
    {
    public:
        TC() : ptr(new T[N]) { }
    private:
        T* ptr;
    };
    
    TC<int[4]> dynamic_array_of_4_ints;
    

    虽然这介于 std::array&lt;T, N&gt; astd::vector&lt;T&gt; v(N) 之间,而且可能比两者都差。

    【讨论】:

      猜你喜欢
      • 2011-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-26
      相关资源
      最近更新 更多