C++ - 为 std::vector 创建新的构造函数<double>?

C++ - create new constructor for std::vector<double>?

本文关键字:lt double gt 构造函数 std vector C++ 创建      更新时间:2023-10-16

我已经编写了一个自定义容器类,它包含一个std::vector<double>实例,工作得很好。为了与其他API兼容,我想将容器的内容导出为std::vector<double>副本。目前这项工作:

MyContainer container;
....
std::vector<double> vc(container.begin(), container.end());

但如果可能的话,希望能够写:

MyContainer container;
....
std::vector<double> vc(container);

我能(轻松地)创建这样一个std::vector<double>构造函数吗?

您可以创建到std::vector<double>:的显式转换

explicit operator std::vector<double>() const {
    return std::vector<double>(begin(), end());
}

然后,std::vector<double> vc(container);将调用std::vector<double>移动构造函数。

请注意,计算成本高昂的转换通常是不受欢迎的。因此,向量工厂函数可能是一种更明智的方法:

class MyContainer {
public:
    using value_type = double;
    // ...
};
template<typename Source>
auto to_vector(Source source) {
    return std::vector<typename Source::value_type>(source.begin(), source.end());
}

然后你会写:

MyContainer container;
// ...
auto vc = to_vector(container);

这也更通用,因为它适用于任何具有兼容value_typebeginend成员的对象。

我能(轻松地)创建这样一个std::vector构造函数吗?

不可以,因为这需要更改std::vector类声明。

不过,您可以为MyContainerstd::vector<double>提供强制转换运算符。

您不能也不应该更改您自己没有编写的类的API。但我认为在你的情况下,演员会做得很好。例如(这个需要-std=c++11):

#include <iostream>
#include <vector>
struct Foo
{
  operator std::vector<double> () const
  {
    return std::vector<double> { 1, 2, 3 };
  }
};
int main()
{
  Foo foo;
  std::vector<double> bar = foo; // Applies the cast operator defined in Foo
  std::cout << bar.size() << std::endl; // Prints "3"
  return 0;
}