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?

2
  • 1
    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). Commented Jul 22, 2010 at 17:49
  • Oversight fixed. The problem with the extra default constructors remains... Commented Jul 22, 2010 at 18:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.