Re: Avoiding copying of an object
On 26 Sep., 11:06, Adam Markiewicz wrote:
I'm designing a container class similar to those in STL. It is implemente=
d
as a template with two parameters: contained type and an allocator.
template <typename Type, typename Allocator>
class FixedArray
{
...
}
Now, to write a function that takes FixedArray as a param to support
different allocators I would need (example):
template <typename Allocator>
float average(const FixedArray<float, Allocator>& array);
However array is const, so Allocator wouldn't be needed at all. Is would =
be
much simpler to write:
float average(const FixedArray<float>& array);
This syntax can be provided by specifying a suitable copy constructor, bu=
t
I want to avoid unnecessary copying overhead. Is there some other
clean solution to this problem?
Making 'average' a function template might not be a bad idea. What if
you also need it for T=double, T=complex<float>, etc? The STL-way of
writing such a function would be to make it a template that accepts a
pair of iterators. See std::accumulate.
Another solution would be to use inheritance:
template<class T>
class fixed_array_base
{
public:
std::size_t size() const {return end_ - begin_;}
T & operator[](std::size_t idx)
{ assert(idx<size()); return begin_[idx]; }
T const& operator[](std::size_t idx) const
{ assert(idx<size()); return begin_[idx]; }
protected:
fixed_array_base() : begin_(0), end_(0) {}
~fixed_array_base() {}
T* begin_;
T* end_;
private:
fixed_array_base(fixed_array_base const&);
fixed_array_base& operator=(fixed_array_base const&);
};
template<class T, class Alloc = std::allocator<T> >
class fixed_array : public fixed_array_base<T>
{
public:
explicit fixed_array(std::size_t n, Alloc const& a = Alloc());
fixed_array(fixed_array const&);
fixed_array& operator=(fixed_array const&);
~fixed_array();
private:
Alloc allocator_;
};
which could be used like this:
float average(fixed_array_base<float> const& fa);
float test() {
fixed_array<float,custom_alloc> numbers (100);
for (int k=0; k<100; ++k)
numbers[k] = k;
return averate(numbers);
}
HTH,
SG