【问题标题】:Is it possible to add own constructor for std::array type?是否可以为 std::array 类型添加自己的构造函数?
【发布时间】:2018-07-19 10:17:59
【问题描述】:

我尝试为std::array 类型添加自己的构造函数,但我不确定这是否可能以及如何做到这一点...

我试过这样的:

typedef unsigned char byte_t;

namespace std {
  template<std::size_t _Nm>
  array::array(std::vector<byte_t> data)
  {
    // Some content
  }
}

我想创建一个非常简单的机制来将std::vector&lt;byte_t&gt; 转换为std::array&lt;byte_t, size&gt;

  1. 有可能吗?
  2. 我该怎么做?

我正在使用 C++14(我不能在我的项目中使用更新的标准)

【问题讨论】:

  • 仅供参考,向 std 命名空间添加东西通常是 UB。
  • @user202729 总是 UB 吗?即使我尝试为自己定义的类型调整标准数据容器?
  • 写一个像make_array这样返回数组并将向量作为参数的函数会更简单
  • 允许向namespace std 添加代码的情况非常有限。这无关紧要,因为您不能在 namespace std 或不拥有的类中添加构造函数。仅供参考std::array 没有构造函数按设计

标签: c++ c++14 stdvector stdarray constructor-overloading


【解决方案1】:

构造函数是特殊的成员函数,它们必须在类定义中声明。在不更改类定义的情况下,无法将构造函数添加到现有类。

您可以使用工厂函数实现类似的效果:

template<size_t N, class T>
std::array<T, N> as_array(std::vector<T> const& v) {
    std::array<T, N> a = {};
    std::copy_n(v.begin(), std::min(N, v.size()), a.begin());
    return a;
}

int main() {
    std::vector<byte_t> v;
    auto a = as_array<10>(v);
}

【讨论】:

  • 更不用说 vector 的大小在运行时是已知的,但 array 的大小必须在编译时已知...
  • @ildjarn 我知道,我有一个解决方案
【解决方案2】:

我怀疑这种转换的必要性,除了需要 std::array 且无法修改的函数。你有两种选择:

  1. Use the good old T* raw array underneath the vector。毕竟,std::array 旨在轻松管理固定大小的 C 数组。
  2. 使用迭代器上的函数使您的代码不知道容器。这是现代 c++ 所期望的设计路径。你可以看看various operations in the algorithm library的可能实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-18
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2021-07-09
    • 2021-02-01
    • 2016-02-16
    相关资源
    最近更新 更多