I am playing around with c++ and faced this question
if I have a variant that looks like this:
using Fruit = variant<Apple, Tomato>
and a vector of unique_ptr of variant:
vector<unique_ptr<Fruit>> fruits
how can I move a unique_ptr<Apple>
into the fruits
vector?
here is an example piece of code:
#include <variant>
#include <memory>
using namespace std;
struct Apple {};
struct Tomato {};
using Fruit = variant<Apple, Tomato>;
int main() {
vector<unique_ptr<Fruit>> fruits;
unique_ptr<Apple> apple = make_unique<Apple>();
fruits.push_back(unique_ptr<Fruit>(move(apple))); // error here
}
on the call to push_back
I get this error:
No matching conversion for functional-style cast from 'remove_reference_t<unique_ptr<Apple, default_delete<Apple>> &>' (aka 'std::unique_ptr<Apple>') to 'unique_ptr<Fruit>' (aka 'unique_ptr<variant<Apple, Tomato>>')
if I change the line to fruits.push_back(unique_ptr<Apple>(move(apple)));
I get this error:
No matching member function for call to 'push_back'
and if I change it to fruits.emplace_back(unique_ptr<Apple>(move(apple)));
no error occurs.
so is using emplace_back
the right choice here? why does this error occur? I am assuming it is because I can’t cast a unique_ptr<VariantMemberType>
to unique_ptr<VariantType>
?
Mahmoud Hany is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.