用于数组的C++模板,并了解它们的大小

C++ template for arrays and knowing their size

本文关键字:了解 数组 C++ 模板 用于      更新时间:2023-10-16

我有一堆结构,比如:

struct A { ... }
struct B { ... }
struct C { ... }

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

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);

由于过程函数实际上是运算符<lt;()(我只是把流程用于演示目的)

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

数组到指针的衰减非常非常糟糕。

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

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

您可以使用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)
   {
      //...
   }
}

或者您可以使用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);

您需要对数组使用以下格式:

template <typename T, size_t N>
void foo(const T (&arr)[N]) {
    ...
}

否则,大小信息将丢失。

或者,一个简单的模板边界检查数组。

template< typename T, unsigned int Size >
class Array
{
    public:
    T& operator[]( unsigned int index )
    {
       assert( index < Size );
       return mElements[ index ];
    }
    const T& operator[]( unsigned int index ) const
    {
       assert( index < Size );
       return mElements[ index ];
    }
    unsigned int Capacity() const
    {
        return Size;
    }
    private:
        T mElements[ Size ];
};

然后

template< typename T, unsigned int Size >
void Process( Array< T, Size >& array )
{
    for( unsigned int i = 0; i < Size; ++i )
    {
        //use array[i]
    }
}

把它绑在一起

Array< int, 10 > array;
Process( array );

这有点像你自己的解决方案,但它可能大致等同于std::array或boost