Search code examples
c++boostboost-variant

Problem with the copy constructor of an class holden in boost::variant


I've tried to construct a tree structure using boost::variant and now I have some problems. I implemented a copy constructor in the class holden in boost::variant and call the copy constructor just like this code:

#include <iostream>
#include <boost/variant.hpp>


struct Hoge{
int i;
Hoge(int j) : i(j){};
Hoge(Hoge const& hoge) : i(hoge.i) {}
};

using var = boost::variant<int,Hoge>;

int main()
{
var hoge = Hoge(1);
var hogehoge = Hoge(hoge);
}

A compile failed because of no matching function for call to ‘Hoge::Hoge(var&)’.

How to fix this code? Should the copy constructor has an argument boost::variant? Or can I fix this code with an brilliant boost technique?


Solution

  • You're not copy constructing: that would be like saying:

    var hogehoge = var(hoge); // elided assign of copy-ctor
    

    Or indeed just

    var hogehoge(hoge);
    var hogehoge = hoge;
    

    So, what you need is to SAY you want a Hoge to copy,

    var hogehoge = boost::get<Hoge>(hoge); // may throw if `hoge` holds int
    

    So you copy-construct Hoge, which you then convert-construct to the variant type.

    See it Live On Coliru

    #include <boost/variant.hpp>
    #include <iostream>
    
    struct Hoge {
        int i;
        Hoge(int j) : i(j){};
        Hoge(Hoge const& hoge) : i(hoge.i) {}
    };
    
    using var = boost::variant<int, Hoge>;
    
    int main() {
        var hoge = Hoge(1);
        var hogehoge = boost::get<Hoge>(hoge);
    }