使用 boost::operators 为模板类定义运算符
我有一个如下所示的类:
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;
}
我应该能够为整数添加相关的比较运算符
class decimal : boost::less_than_comparable<fixed_decimal<DIGITS, DECSIZE>, int>{ }
但如何将 less_than_comparable 与其他十进制模板一起使用? 我希望能够比较十进制<10,5>和例如,十进制<6,4>。
I've got a class which looks like this:
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;
}
I should be able to add related comparison operators for ints with
class decimal : boost::less_than_comparable<fixed_decimal<DIGITS, DECSIZE>, int>{ }
But how can I use less_than_comparable with other decimal templates?
I'd like to be able to compare decimal<10,5> with decimal<6,4>, for example.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为由于 C++ 编译器扩展模板的方式,这是不可能的。您必须为每个
组合定义运算符。在您的位置,我将采取动态方法并使这两个参数成为您的类的成员变量而不是模板参数。I think this is not possible due to the way C++ compilers expand templates. You'd have to define operators for each
<DIGITS, DECSIZE>
-combination. In your place, I'd take a dynamic approach and make those two parameters member variables of your class instead of template parameters.对于返回固定类型的运算符,例如
bool
,您可以手动实现运算符:(当然,有很多更聪明的方法来进行比较。)
但是一旦您涉足以下领域更复杂的算术表达式,例如运算符 +,这不再那么容易完成,因为返回类型取决于(目前未知)模板参数。
您可以在C++11中执行如下操作:
...并调用:
如果您不能使用C++11,那么您需要使用模板元函数而不是普通函数/重载运算符。
For operators that return a fixed type such as
bool
, you can implement the operators manually:(Of course, there are much cleverer ways to do the comparison.)
But as soon as you foray into the realms of more complex arithmetic expressions such as
operator +
this can no longer be done as easily, since the return type depends on (as of yet unknown) template arguments.You can do it in C++11 as follows:
… and to invoke:
If you cannot use C++11, then you need to use template metafunctions instead of normal functions / overloaded operators.