Leopoldo
Leopoldo

Reputation: 825

Confused about templates

I have to deal with a code, which I am totally confused about.

#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;
}

Could you comment about following line?

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

How greater and less operator is used here?

I cannot figure out how second template is used:

template<bool b>

Upvotes: 2

Views: 195

Answers (2)

thus spake a.k.
thus spake a.k.

Reputation: 1637

Note that the default constructor T() zero initialises built in types. So

B<(t > T())>::m_n

is 1 if t is positive and 0 otherwise, and

B<(t < T())>::m_n

is 1 if t is negative and 0 otherwise. Hence

B<(t > T())>::m_n - B<(t < T())>::m_n

is 1 if t is positive, 0 if it is zero and -1 if it is negative.

Upvotes: 3

B is a (nested) class template with a bool template parameter (b); its static member m_n is 1 when b is true, and 0 when b is false.

t > T() tests whether the value t (which is a template parameter of A) is greater than a value-initialised T. Since T must be a valid type for non-type template parameters, T() is equivalent to T(0), i.e. a zero expressed in the correct type.

The result of that test is then used as a template argument for B. Equivalent code would look like this:

public:
    static const T t0 = T();
    static const bool b1 = t > t0;
    static const bool b2 = t < t0;
    static const int m_value = B<b1>::m_n - B<b2>::m_n;

Upvotes: 5

Related Questions