General C++ Template class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

#include <iostream>

template<class T, T t = T()>
class A
{
private:
    template<bool b>
    class B
    {
    public:
        static const int m_n = b ? 1 : 0;
    };

public:
    static const int m_value = B<(t > T())>::m_n - B<(t < T())>::m_n;
};

int main()
{
    std::cout << A<int, -9>::m_value
              << A<bool, true>::m_value
              << A<char>::m_value << std::endl;

    return 0;
}


Can someone explain why the output of the above program is:

-110
A performs three-way comparison between its second template parameter t and the value-initialized value of the type T.
If t is greater than T(), it sets m_value to 1
if t is equivalent to T() (not less and not greater), it sets m_value to 0
if t is less than T(), it sets m_value to -1.

-9 is less than int() (which is zero), so A<int, -9>::m_value is -1
true is greater than bool() (which is false), so A<bool, true>::m_value is 1
char() equals char(), so A<char>::m_value is 0

To see how this happens, just substitute the arguments into the parameters, for example, for T = int, t = -9, you get
m_value = B<(-9 > 0)>::m_n - B<(-9 < 0)>::m_nthat is,
m_value = B<false>::m_n - B<true>::m_nsubstituting false and true into B, you will get
m_n = false ? 1 : 0; and m_n = true ? 1 : 0 respectively, so the above becomes
m_value = 0 - 1
Last edited on
Cubbi,

Many thanks.
It is clear now.

Kind regards
Topic archived. No new replies allowed.