|
Boost Users : |
Subject: Re: [Boost-users] C++ guru required!
From: Maxim Yanchenko (maximyanchenko_at_[hidden])
Date: 2012-02-27 03:21:36
Robert Ramey <ramey <at> rrsd.com> writes:
> Anyway, I did get what i wanted from my question - I can
> just use if(... dependent on a template paramter) whereever
> it makes syntactical sense and get what I expect to get.
It's not just this.
In case of normal if, both branches are being compiled (even if one branch will
be discarded later), but in case of static if (or any other existing replacement
like enable_if, overloading by true_type/false_type etc) only one branch is is
compiled.
So of course you can't use normal if when the branches can't be compiled at the
same time (this is what you call "syntactical sense"), but even when they can be
compiled together it may be not the best way to go.
The reason is: this stuff usually appears in template code, so it usually calls
other templates in turn, and the number of instantiations needed to compile both
branches can be huge, and you'd probably wanted to avoid this.
It's basically the same reasoning as with checking template arguments: it's
better to check all of them first and only if all args are ok call another
function that will do the work, otherwise call an empty function that will just
report the error (and select between them statically via true_type/false_type
overload).
If you don't do this and just write one big function that has all that checks in
the beginning, even in the case of check failure the compiler will continue to
compile the rest of the body, instantiating more and more templates and printing
more and more errors.
So the real answer is: you need static if (or any other replacement) when you
don't want the compiler to try to compile the unneeded branch (whether it will
give an error if compiled or it's just too heavy to compile).
Thanks,
Maxim
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