复杂的运算符重载和模板

And*_*eev 1 c++ templates operator-overloading friend

这是C++中非常疯狂的定点运算实现.请不要评论这是多么糟糕和毫无意义.

如您所见,小数部分有一个基本类型T一些二进制数字N.需要FixedNum<int, A> + FixedNum<int, B>进行评估.FixedNum<int, MAX(A, B)>.以下是我尝试实现它的方法.但是,海湾合作委员会表示,x最后一行的任务是错误的,因为x受到保护.怎么了?

#define MAX(a,b) (((a)>(b))?(a):(b))

template <typename T, int N>
class FixedNum
{
    public:
        template <int N2>
        friend FixedNum& operator+(const FixedNum& f, const FixedNum& g);
        template <int N2>
        friend FixedNum& operator+=(const FixedNum& f, const FixedNum& g);
        FixedNum(T x): x (x) {}

        T num() const { return x; }
        int point() const { return N; }

    protected:
        T x;
};

template <typename T, int N, int N2>
FixedNum<T, MAX(N, N2)>& operator+(const FixedNum<T, N>& f, const FixedNum<T, N2>& g)
{
    return FixedNum<T, N>(f) += g;
}

template <typename T, int N, int N2>
FixedNum<T, MAX(N, N2)>& operator+=(const FixedNum<T, N>& f, const FixedNum<T, N2>& g)
{
#if N2 <= N
    f.x += g.x << (N-N2);
#else
    f.x <<= (N2-N);
    f.x += g.x;
#endif
}
Run Code Online (Sandbox Code Playgroud)

πάν*_*ῥεῖ 5

您必须使用bool选择器模板并将其专门化N2 <= N而不是使用#if #else #endif.预处理器根本不会看到模板实例化.