ankith13
ankith13

Reputation: 391

how to call the particular constructor of boost::variant

I have a problem of calling the constructors in boost::variant. Suppose I have two classes "abc" and "asd" and I have an object declaration something like-

class abc
{
   int var;
   float var2;
   public: abc(int a)
           {
             var = a;
            }
   public: abc(inta, float b)
            :var(a), var2(b)
            {}
 };

 class asd
 {
   int var;
   public: asd(int a)
           {
               var = a;
           }
  };

typedef boost::variant<abc,asd> def;
int main()
{
    def my_object;
}

my problem is how do I call the constructor of the object my_object?

Upvotes: 1

Views: 2606

Answers (2)

sehe
sehe

Reputation: 393694

A variant is not some multiply-derived custom type, and has its own constructors defined instead. The idiomatic way is to just assign one of the variant types:

typedef boost::variant<abc,asd> def;
int main()
{
    def my_object = abc(1);

    my_object = abc(1, .4);
}

If you wanted to actually use constructor without without copy-initialization (allthough most compilers will elide the copy) you can write:

def my_object(abc(1,.4));

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385325

From the manual (you must have missed it):

a variant can be constructed directly from any value convertible to one of its bounded types

And:

Similarly, a variant can be assigned any value convertible to one of its bounded types

So:

def my_object = asd(3); // or `def my_object(asd(3));`
my_object = abc(4);

Upvotes: 2

Related Questions