Boost logo

Boost Users :

Subject: Re: [Boost-users] C++ guru required!
From: Christopher Jefferson (chris_at_[hidden])
Date: 2012-02-19 06:58:35

On 17 Feb 2012, at 20:40, Robert Ramey wrote:

> I've got a really dumb question. My question is illustrated by the
> following
> code snippit.
> template<class T, class U>
> T inline operator%(const T & lhs, const U & rhs) {
> if(0 == rhs)
> throw std::domain_error("Divide by zero");
> if(boost::is_same<T, boost::uintmax_t>::value
> && boost::numeric::is_signed<U>::value
> ){
> if(1 == rhs || -1 == rhs) // is this dropped?
> overflow("unsigned type can hold this result");
> }
> return lhs % rhs;
> }
> I would like to think that the second if is always
> dropped from the compile for a particular pair
> of types since this can be evaluated at compile time.
> If I'm correct, I can replace some tedious
> template metaprogramming for some straightforward
> and transparent code inserted in a convenient code
> inserted in the most convenient place.
> Andre Alex... gave a talk at "Going Native" proposing
> a "static if" for this case. But I don't see the necessity for
> for this since I would assume that the compiler
> just optimises away the "dead" code. I've compiled
> the above and it seems to do what I want but
> still I wonder.
> Basically I see lots of applications of variations
> on this idea to get the benefits of tmp without
> the attendent pain.
> Am I missing anything here?

No, you are missing nothing at all. The normal reason you have to use TMP is because inside of the if won't compile for one set of types.

You can be sure that this code will be removed. gcc will remove it even without optimisation turned on. Switching to TMP will remove the code, but a compiler so terrible that it doesn't do dead code elimination probably wouldn't also inline the TMP functions, leading to more overhead anyway.

If you ever want to see what g++ gets up to in a (reasonably) readable fashion, add '-fdump-tree-all', and read the output with the highest number, which isn't statistics. Note that this isn't all the optimisation gcc does, but covers much of the high-level optimisation.


Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at