问题
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 e.g. std::vector
?
回答1:
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.
来源:https://stackoverflow.com/questions/40599052/how-to-write-a-wrapper-for-stdarrays-list-initialization-constructor