简体   繁体   中英

How to write a wrapper for std::array's list initialization constructor?

I'm writing a wrapper that, for the purpose of this question, does nothing but wraps a SequenceContainer ( http://en.cppreference.com/w/cpp/concept/SequenceContainer ) and reproduces all functionality of the SequenceContainer concept the wrapped container offers.

My attempt to write such a wrapper looks like this:

template<class Container>
class SequenceContainerWrapper
{
  Container cont;
public:
  using value_type = typename Container::value_type;
  using reference = typename Container::reference;
  using size_type = typename Container::size_type;
  SequenceContainerWrapper(initializer_list<value_type> init) : cont(init) {}
  reference operator[] (size_type n) {return cont[n];}
  // lots of other code that does nothing but wrapping
};

And yes – I can use it, for example, with std::vector . The below code compiles and works as expected ( http://ideone.com/sYeIeJ ):

int main()
{
    SequenceContainerWrapper<vector<int>> vec({1,2,3,4});
    cout << vec[2] << '\n';
}

However, this constructor won't work with std::array . This snippet does not compile ( http://ideone.com/5nZhar ):

int main()
{
    SequenceContainerWrapper<array<int, 4>> arr({1,2,3,4});
    cout << arr[2] << '\n';
}

This is because ( http://en.cppreference.com/w/cpp/concept/SequenceContainer#cite_note-1 ):

std::array supports assignment from a braced-init-list, but not from an std::initializer_list

So how can I reproduce in my wrapper the possibility to initialize an std::array with a braced-init-list without sacrificing the genericness of my wrapper and introducing solutions that will cripple the wrapper's compatibility with eg std::vector ?

Instead of using:

SequenceContainerWrapper(initializer_list<value_type> init) : cont(init) {}

you could use:

SequenceContainerWrapper(Container init) : cont(std::move(init)) {}

See it working at http://ideone.com/MzRQGC .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM