简体   繁体   中英

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

I have written a custom container class which contains a std::vector<double> instance - works nicely. For compatibility with other API's I would like to export the content of the container as a std::vector<double> copy . Currently this works:

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

But if possible would like to be able to write:

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

Can I (easily) create such a std::vector<double> constructor?

You can create an explicit conversion to std::vector<double> :

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

Then, std::vector<double> vc(container); will invoke the std::vector<double> move constructor.

Note that conversions that are computationally expensive are generally frowned upon. Therefore, a vector factory function may be a wiser approach:

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

Then you'd write:

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

This is also more generic as it works with anything that has compatible value_type , begin and end members.

Can I (easily) create such a std::vector constructor?

No you can't, since this would require to change the std::vector class declarations.

You can provide a cast operator for MyContainer to std::vector<double> though.

You cannot, and should not, change the API of a class you didn't write yourself. But I think in your case a cast operator would do just fine. For example (this one needs -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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM