对模板感到困惑

Leo*_*ldo 2 c++ templates class

我必须处理一个我完全困惑的代码.

#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;
}
Run Code Online (Sandbox Code Playgroud)

你能评论下面的一行吗?

static const int m_value = B<(t > T())>::m_n - B<(t < T())>::m_n;
Run Code Online (Sandbox Code Playgroud)

如何更大更少的操作者用在这里?

我无法弄清楚如何使用第二个模板:

template<bool b>
Run Code Online (Sandbox Code Playgroud)

Rei*_*ica 5

B是一个带有bool模板参数(b)的(嵌套)类模板; 它的静态成员m_n1时候btrue0bfalse.

t > T()测试值t(模板参数为A)是否大于初始值T.由于T必须是非类型模板参数的有效类型,T()因此等效于T(0),即以正确类型表示的零.

然后将该测试的结果用作模板参数B.等效代码如下所示:

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;
Run Code Online (Sandbox Code Playgroud)