|
Boost : |
Subject: Re: [boost] [static_if] Is there interest in a `static if` emulation library?
From: Mathias Gaunard (mathias.gaunard_at_[hidden])
Date: 2014-09-08 06:35:13
On 03/09/2014 07:19, Robert Ramey wrote:
> here is the original example:
>
> template< typename T >
> void assign ( T& x, T const& y ) {
> x = y;
> if(boost::has_equal_to<T>::value){
> assert(x == y);
> std::cout << "asserted for: " << typeid(T).name() << std::endl;
> }
> else {
> std::cout << "cannot assert for: " << typeid(T).name() <<
> std::endl;
> }
> }
>
> depending on the type of T, only one of the branches need be compiled.
> Whatever is done with the other branch will be thrown away so what's the
> point of compiling it. Of course the the C++ parser has to determine where
> the branches start an end, but that's way, way short of doing full
> compilation of the unused branch.
Consider the following:
template<class T>
void foo(T const& t)
{
if(has_toint<T>::value)
{
int a = t.toint();
std::cout << a << std::endl;
}
else
{
int a = 0;
std::cout << 0 << std::endl;
}
}
In branch 1, T must have a .toint() member, returning a value
convertible to int.
If T doesn't have a toint member, the code above will not compile, even
though there is a branch for it. This is why static if was invented.
Now: why couldn't the compiler realistically avoid to instantiate the
non-taken branch automatically?
To avoid inconsistencies, you would need to make sure that there are no
side-effects to not instantiating that branch.
That alone is a big problem, instantiating templates has side effects,
that most compilers are not able to diagnose in any capacity, and any
statement could instantiate any template anywhere.
Even if you could, the obvious side effect would be that the code fails
to compile, so you can't possibly be consistent if you choose to ignore
a branch.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk