0

I define my own variant type like so:

typedef variant<myobj **, ... other types> VariantData;

One of my class methods gets this data type as a parameter and tries to do something like:

void MyMethod(VariantData var){
    //method body
    if(some_cond){ // if true, then it implies that var is of type
                   // myobj **
        do_something(*var); // however, I'm unable to dereference it
    }
    // ... ther unnecessary stuff
}

As a result, when I compile my program, I get this error message:

error: no match for 'operator*' (operand type is 'VariantData ....'

I do not know how to fix this error. PS. On the whole the code works well - if I comment out this part related to dereferencing, then everything runs smoothly.

Igor R.
  • 14,716
  • 2
  • 49
  • 83
Jacobian
  • 10,122
  • 29
  • 128
  • 221
  • You can't dereference `boost::variant`. Use a [static visitor](http://www.boost.org/doc/libs/1_58_0/doc/html/variant.html#variant.motivation) or [get()](http://www.boost.org/doc/libs/1_58_0/doc/html/boost/get_idp295310448.html) function (which is not type-safe) to extract the value – Igor R. Aug 02 '15 at 19:10
  • I think, if you elaborate a little bit on this, you can make an answer. I will appreciate it and accept it. – Jacobian Aug 02 '15 at 19:12
  • Documentation does not seem to be rather informative, especially in terms of examples. As for me, I think that `get` function suits me better, but I can't figure out from documentation, how to use it. – Jacobian Aug 02 '15 at 19:17
  • How, for example, should I `get` a variable of type `myobj **` out of a `var` variable? – Jacobian Aug 02 '15 at 19:19

1 Answers1

1

The error message is quite self-explanatory: you can't dereference boost::variant, it doesn't have such semantics. You should first extract the value, i.e. the pointer, and then dereference it.

To extract the value relying on a run-time logic, just call get():

//method body
if(some_cond){ // if true, then it implies that var is of type myobj **
    do_something(*get<myobj **>(var));
}

Note, however, that if the run-time logic fails (eg. due to a bug), get() will throw bad_get exception.

Igor R.
  • 14,716
  • 2
  • 49
  • 83