C++ 使用boost::operators为模板类定义运算符

C++ 使用boost::operators为模板类定义运算符,c++,boost,C++,Boost,我有一门课看起来像这样: template<int DIGITS, int FRACTIONS> class decimal{ bool operator<(const int& rhs) const; template<int RDIGITS, int RFRACTIONS> bool operator<(const decimal<RDIGITS, RFRACTIONS>& rhs) const; }

我有一门课看起来像这样:

template<int DIGITS, int FRACTIONS>
class decimal{

    bool operator<(const int& rhs) const;

    template<int RDIGITS, int RFRACTIONS>
    bool operator<(const decimal<RDIGITS, RFRACTIONS>& rhs) const;
}
模板
类小数{

BOOL运算符< P>由于C++编译器扩展模板的方式,这是不可能的。您必须为每个<代码> <代码>组合定义运算符。在您的位置,我将采取动态方法,使类的两个参数成员变量而不是模板参数。
bool
,您可以手动实现这些操作符:

template <int N1, unsigned D1, int N2, unsigned D2>
bool operator <(fraction<N1, D1>, fraction<N2, D2>) {
    // Normalisation omitted, using floating point arithmetic
    return (static_cast<float>(N1) / D1) < (static_cast<float>(N2) / D2);
}
…并援引:

fraction<1, 2> a;
fraction<3, 2> b;
auto c = a + b;
分数a;
b组分;
自动c=a+b;

如果您不能使用C++11,那么您需要使用模板元函数,而不是普通函数/重载运算符。

不幸的是,我们不能这样做,因为实例必须在内存中对齐。另外,我不确定如何最好地定义这些函数:按值获取它们的参数或作为
常量&
。两种方法都有效。有趣的问题。
template <int N1, unsigned D, int N2>
constexpr auto operator +(fraction<N1, D>, fraction<N2, D>)
    -> fraction<N1 + N2, D>
{
    return fraction<N1 + N2, D>();
}
fraction<1, 2> a;
fraction<3, 2> b;
auto c = a + b;