关于 std::array 的初始化
假设您有一个模板类的 c++0x std::array 成员,并且您希望通过带有几个迭代器的构造函数来初始化它:
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;
};
假设您提供与存储大小一致的范围,是否可以在构造函数初始值设定项中初始化 std::array,避免存储中 Tps 的多余默认构造函数?是否可以利用 std::initializer_list<>在这种情况下?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不。
std::array
是一个聚合,因此您不会获得像采用迭代器的构造函数这样的特殊功能。 (这实际上让我感到惊讶,随着std::initializer_list
的引入,我认为创建其他有用的构造函数没有什么坏处。也许有一个问题。)这意味着使用迭代器复制数据的唯一方法在数组内部进行迭代,为此,数组必须已经构造完毕并可供使用。
No.
std::array
is an aggregate, so you get no special functionality like constructors taking iterators. (This actually surprises me, with the introduction ofstd::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.