[英]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. 我正在编写一个包装程序,出于这个问题的目的,它只包装了SequenceContainer( http://en.cppreference.com/w/cpp/concept/SequenceContainer ),并重现了包装好的SequenceContainer概念的所有功能集装箱报价。
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
. 是的,例如,我可以将其与
std::vector
。 The below code compiles and works as expected ( http://ideone.com/sYeIeJ ): 以下代码可以按预期方式编译和运行( 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
. 但是,此构造函数不适用于
std::array
。 This snippet does not compile ( http://ideone.com/5nZhar ): 该代码段无法编译( 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 ): 这是因为( 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
std :: array支持通过括号初始列表进行赋值,但不支持通过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
? 那么,如何在包装器中重现用括号初始列表初始化
std::array
的可能性, 而又不牺牲包装器的通用性,并引入一些会破坏包装器与例如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 . 在http://ideone.com/MzRQGC上查看它的工作原理 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.