Re: Why is 'Variant' used in so many contexts?
On Jul 21, 2:33 pm, Eugene Gershnik <gersh...@hotmail.com> wrote:
On Jul 20, 9:06 am, Kirit Sflensminde <kirit.saelensmi...@gmail.com>
wrote:
Think about a COM VARIANT that might be a string, an int or a double.
Everytime you read the value you'll have something like:
[...]
No. One time before using COM variant you write a visitor pattern
wrapper around it. It takes about an hour. Then your code looks
identical to the version using boost.
That still doesn't make it type safe in the same way because it
doesn't stop something else from being put into the variant. What
you're doing with your wrapper is to centralise the location of the
type check, which still occurs at run time. With the boost::variant
the type check occurs within the compiler and it is done on assignment
and when the item is pulled out.
Notice that we've abstracted out the switch statement, and even better
we've swapped the runtime check for a compile time type check!
I didn't look at boost::variant implementation but I very strongly
suspect that all you did was to swap runtime check for a virtual
function call. Both are runtime things and impose some overhead.
No it doesn't. There are no virtual methods in the boost::variant code
and the type testing is done within the compiler. If you forget to
supply one of the members for a type wrapped in the variant you get a
compile time error. E.g.
struct process : public boost::static_visitor< void > {
void operator()( int i );
void operator()( double d );
//void operator()( const std::string & );
};
This will now fail with an error when it attempts to compile it.
Uncomment the std::string handler and it will compile again. However
if you comment out the int handler it will work as the int will be
promoted to double (again by the compiler).
It is possible to write a COM variant wrapper that does the same sort
of thing, but as you cannot restrict what is put into a COM variant
(at least if you're taking them from some external source which is the
only real reason to use them) you always have the possibility of a run-
time type failure that is not possible with the boost::variant.
By type tests here I'm not really talking about the sorts of things
that C++ developers think about as type checking. Strongly typed
languages can do much more than that.
K
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]