Boost logo

Boost Users :

Subject: [Boost-users] create type inside boost::variant without calling copy constructor
From: Maxim Koshelev (chuchelo_at_[hidden])
Date: 2009-01-20 02:44:22


Hi, all!

At first small example which introduce problem and solutions.

Let's write class that hold some object and give us access to it (it's
not for real usage, only for demonstration):

class Holder{
    struct Impl{};

    template<typename T_>
    struct Impl{
         T_ val;
          Impl(const T_ &v):val(v){}
    };
    Impl *v_;
public
   template<typename T_>
   Holder(const T_&val):v_(new Impl<T_>(val)){};

   template<T_>
   T_ get(){ dynamic_cast<T_>(*v_); };
};

now we have a constructor which create Holder with some type inside
by copying it. If we want to create Holder with some type without
copying, just created by default constructor, we can use "traits"
technics:

template<typename T_>
class Trait{
 typedef T_ type;
}

template<typename T_>
Holder(const Trait<T_>):v_(new Impl<T_>){};

and when we want to create Holder with some type inside we use:

Holder v( Trait<SomeType>() );

And now problem: is there any way to create boost::variant with a type
inside without calling copy constructor? Currently I see only one way:

boost::variant< std::string, std::pair<std::string, std::string> > p;

p=std::string();

in this code we create "empty" variant variable "p", then copy empty
string inside it. But I need just create p with std::string inside,
without copying! Any solution?

Thanks in advance, and additional thanks if you have read till this
sentence :-)

P.S. Sorry for my ugly English :-)


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net