如何为std :: array的列表初始化构造函数编写包装器? [英] How to write a wrapper for std::array's list initialization constructor?

查看:91
本文介绍了如何为std :: array的列表初始化构造函数编写包装器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个包装程序,出于这个问题的目的,它只包装了SequenceContainer( http://en.cppreference.com/w/cpp/concept/SequenceContainer ),并复制包装容器提供的SequenceContainer概念的所有功能。

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
};

是的,例如–我可以将其与 std ::一起使用:向量。下面的代码可以按预期方式编译和运行( http://ideone.com/sYeIeJ ):

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';
}

但是,此构造函数不适用于 std :: array 。此代码段无法编译( http://ideone.com/5nZhar ):

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';
}

这是因为( http://en.cppreference.com/w/cpp/concept/SequenceContainer#cite_note-1 ):


std :: array支持通过括号初始化列表进行赋值,但不支持通过std :: initializer_list进行赋值

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

所以我如何在包装器中重现用括号括起来的 std :: array 的可能性, init-list ,而不会牺牲包装器的通用性,并引入了一些解决方案,这些解决方案将削弱包装器的兼容性,例如 std :: vector

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?

推荐答案

而不是使用:

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

您可以使用:

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

请参见 href = http://ideone.com/MzRQGC rel = nofollow noreferrer> http://ideone.com/MzRQGC

这篇关于如何为std :: array的列表初始化构造函数编写包装器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆