Construction from Array
I'm developing a simple co开发者_Python百科ntainer class for C++ and I realized it would be helpful to be able to copy values from an array.
It's the difference between this:
myClass myInstance;
myInstance += 2;
myInstance += 4;
myInstance += 8;
myInstance += 16;
And this:
myClass myInstance;
int myArray[] = {2, 4, 8, 16};
myInstance = myArray;
Obviously, the array construction is a lot cleaner. However, since you can't get the size of an array passed to a function (in this case, operator=
), copying the values is an issue.
I could pass the size as a parameter along with the array, but that means I can't use operator=
:
myInstance.getArrayValues(myArray, 4);
Is a whole lot less intuitive than
myInstance = myArray;
How are things like this usually handled?
Actually, you can accept native arrays by reference. Here is an example of assignment operator that does what you want:
template <std::size_t N>
const myClass& operator=(const int(&arr)[N])
{
// use arr as you do usually with arrays :)
// N is the size of the array.
return *this;
}
The best way is probably to use iterators, i.e. give your class a templated function that takes in a first and last iterator, which would of course be able to use pointers as well.
The benefit is that you would then be able to take inputs from any container.
Or you could wait for C++0x support in your compiler and make use of the new functionality that allows construction using initialization lists like for an array, if I remember correctly. Until then, using iterators is the way to go I think.
The Boost.Assignment library was designed to tackle this issue.
The standard handles it in the std::vector
template class (and TR1 has a std::array
class for C-style arrays that do not change size/capacity).
std::vector
accomplishes what you want (again, without overloading operator=
) by using the insert and assign functions.
精彩评论