c++ - Pass an object of a type aggregated by a boost::variant to a function that accepts that boost::variant -


suppose have:

class typea { }; class typeb { }; typedef boost::variant<typea, typeb> type; 
  1. this ok:

    void foo(type t) { };  int main(){     typea a;     foo(a); } 
  2. this not compile:

    void foo(type &t) { };  int main(){     typea a;     foo(a); } 

    with error:

    invalid initialization of reference of type ‘type&’ expression of type ‘typea’

  3. also not compile:

    void foo(type *t) { };  int main(){     typea a;     foo(&a); } 

    with error:

    cannot convert ‘typea*’ ‘type*’ argument ‘1’ ‘void foo(type*)’

is there way pass function accepts boost::variant instance of 1 of types aggregated boost::variant, either through reference (as in case 2) or pointer (as in case 3)?

thank much!

what happens in 1:

typea a; type __temporary__(a); foo(__temporary__); 

what cannot happen in 2 or 3:

typea a; type* __temporary__(&a);   // fails because there no inheritance relationship foo(__temporary__); 

you have 2 solutions (for non template foo):

  • convert type, take pointer/reference this
  • create boost::variant<typea*,typeb*> implicit conversion kick in

a third solution change foo itself, , make template. depends on want do.


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -