我有一堆结构,如:
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);
我无法明确传递数组的大小,因为进程函数实际上是operator&lt;&lt;()(我只是用于演示目的的进程)
更新:我不能在这里使用任何std容器。不幸的是,它必须是一个阵列!
答案 0 :(得分:10)
数组到指针衰减真的,真的坏。
幸运的是,C ++有数组引用,它们知道它们的大小。
template<typename T, size_t N> ostream& process(ostream& os, const T (&arr)[N]) {
// use N
}
答案 1 :(得分: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)
{
//...
}
}
或者您可以使用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);
答案 2 :(得分:1)
您需要对数组使用以下格式:
template <typename T, size_t N>
void foo(const T (&arr)[N]) {
...
}
否则,尺码信息将丢失。
答案 3 :(得分:0)
或者,一个简单的模板边界检查数组。
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
大致相当(虽然功能较少的数组类)