I am wondering, if it’s possible in C++0x to create a statically typed variant, (that behaves like auto) :
variant<int, bool, std::string> v = 45;
When we assign v to a value other than int, it doesn’t compile:
v = true; //Compile error
So far I haven’t found any elegant solution.
This code compiles on my machine with Boost.Variant and g++ 4.5 for both C++98 and C++0x. Do you want to implement a variant-type yourself? Then you might look into the Boost implementation.
In the case that you want to /get/ the above behaviour you could do it like this:
This should be quite equivalent to what you describe.
The following implements Clintons suggestion:
You only need
<memory>and<type_traits>for this and get perfect forwarding and correct behaviour for integer promotion.