Bug#538647: closed by Florian Weimer <fw@deneb.enyo.de> (Re: Bug#538647: g++-4.3: g++ examines second value to "?" always if it is a template)
* Philip Ashmore:
>> * Philip Ashmore:
>>
>>
>>> /*HERE*/enum { value = (wanted <= guess) ? result : next_value_type::value };
>>>
>>
>> Not a bug. You need to implement your own conditional operator at the
>> template level to make this work. The version with ?: is not valid
>> C++
> Not valid C++ ? My C++ compiler (g++) disagrees.
My wording was a bit careless. Technically, it is a valid C++ program
which cannot be compiled by a conforming implementation, no matter
what its implementation limits regarding nested template
instantiations are. However, for practical purposes, it's still
invalid code.
> I don't remember reading anything about "conditional operator at the
> template level" in Stroustrup's "C++ programming language (third
> edition).
It's something like this:
template <bool Test, typename True, typename False> struct ite { };
template <typename True, typename False> struct ite<true, True, False>
{ typedef True value; };
template <typename True, typename False> struct ite<false, True, False>
{ typedef False value; };
I'm no longer sure that it would help the way you structured your
example.
Here's something instead that works:
template <unsigned N> struct log2 {
enum { value = log2<(N >> 1)>::value + 1 };
};
template <> struct log2<0> {
enum { value = -1 };
};
The difference is that template matching stops the recursion. Plain
expressions don't, even if short-cut operators such as &&, ||, and ?:
are involved---at least in ISO C++ (previous language versions and
their implementations were different). This is one reason why
template metaprogramming is so weired.
Reply to: