数组的C++模板并知道它们的大小

chr*_*irk 1 c++ arrays templates struct pointers

我有一堆结构,如:

struct A { ... }
struct B { ... }
struct C { ... }
Run Code Online (Sandbox Code Playgroud)

我想设计一个函数,它可以接受这些结构的数组并遍历数组的每个元素并调用另一个函数,如:

template <typename T>
ostream& process(ostream& os, const T* array) {
   // output each element of array to os (but how do we know the length?)
}

A a_array[10];

process(a_array);
Run Code Online (Sandbox Code Playgroud)

我无法显式传递数组的大小,因为进程函数实际上是operator <<()(我只是用于演示目的的进程)

更新:我不能在这里使用任何std容器.不幸的是,它必须是一个阵列!

Pup*_*ppy 10

数组到指针衰减确实非常糟糕.

幸运的是,C++有数组引用,它们知道它们的大小.

template<typename T, size_t N> ostream& process(ostream& os, const T (&arr)[N]) {
    // use N
}
Run Code Online (Sandbox Code Playgroud)

  • 我总是看到`const T(&arr)[N]`,但我认为它的工作原理是一样的. (2认同)

Fox*_*x32 7

您可以使用std::vector<T>而不是简单的数组.

template <typename T>
ostream& process(ostream& os, const std::vector<T> &array) {
   for(std::vector<T>::const_iterator iterator = array.begin(); iterator != array.end(); ++iterator)
   {
      //...
   }
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用std :: array方式(如果您的编译器支持它并且N是常量).

template <typename T, int N>
ostream& process(ostream& os, const std::array<T, N> &array) {
   for(std::array<T, N>::const_iterator iterator = array.begin(); iterator != array.end(); ++iterator)
   {
      //...
   }
}

// Usage:
array<int, 10> test;
process(..., test);
Run Code Online (Sandbox Code Playgroud)

  • 如果编译器没有`std :: array`,`boost :: array`总是一个选项 (3认同)