On the initialization of std::array [duplicate]
Asked Answered
V

1

8

Let's say you have a c++0x std::array member of a template class and you want to initialize it by means of a constructor that takes a couple of iterators:

template <typename Tp, size_t N>
class Test 
{
public:
    template <typename Iterator>
    Test(Iterator first, Iterator last)
    {
        if (std::distance(first,last) > N )
            throw std::runtime_error("bad range");
        std::copy(first, last, _M_storage.begin());
    }

private:
    std::array<Tp, N> _M_storage;

};

Assuming that you are providing a range congruent with the size of your storage, is it possible to initialize the std::array in the constructor initializer, avoiding the superflous default constructors of Tps in the storage? Is it possible to exploit the std::initializer_list<> in this case?

Vadose answered 22/7, 2010 at 17:7 Comment(2)
By the way, an identifier that starts with an underscore and is followed by a capital letter is reserved. Also, it should be std::distance(first, last).Densmore
Oversight fixed. The problem with the extra default constructors remains...Vadose
D
3

No.

std::array is an aggregate, so you get no special functionality like constructors taking iterators. (This actually surprises me, with the introduction of std::initializer_list I see no harm in making other useful constructors. Perhaps a question is in store.)

This means the only way to use iterators to copy data inside the array is to iterate, and to do that the array must be already constructed and ready to use.

Densmore answered 22/7, 2010 at 17:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.