我正在编写一个 CheckedPtr 类来练习异常处理(Stroustrup,TC++PL 练习,第 4 版,问题 14.1)。我想重载一堆运算符,而执行此操作的代码几乎相同。我正在使用宏来避免过于重复,但我知道宏很危险,所以我想知道是否存在更好的方法。
这是我的代码——显示的部分是我在名为 CheckedPtr 的类中定义的部分。我能做得更好吗,和/或没有宏?我宁愿不手动编写所有这些函数,即使这意味着使用宏会带来一些风险。
// This is relatively dangerous.
#define CHECKED_PTR_OVERLOAD_COMPARATOR(OP) \
template<typename Ptr> \
bool operator OP(Ptr& p) { return pos OP &*p; }
CHECKED_PTR_OVERLOAD_COMPARATOR(==)
CHECKED_PTR_OVERLOAD_COMPARATOR(<)
CHECKED_PTR_OVERLOAD_COMPARATOR(>)
CHECKED_PTR_OVERLOAD_COMPARATOR(<=)
CHECKED_PTR_OVERLOAD_COMPARATOR(>=)
#undef CHECKED_PTR_OVERLOAD_COMPARATOR
最佳答案
正如评论者已经说过的,不要为此使用宏。如果你想有一个最小的实现但是一个完整的集合比较功能,我相信Boost.Operators是你最好的选择。我链接到的页面上显示的示例是:
struct animal : public boost::less_than_comparable<animal>
{
std::string name;
int legs;
animal(std::string n, int l) : name{std::move(n)}, legs{l} {}
bool operator<(const animal &a) const { return legs < a.legs; }
};
在哪里实现单个 operator<
函数并让动物类派生自 boost::less_than_comparable<animal>
给你运算符 >
, <=
, 和 >=
.
stackoverflow上还有其他相关问题。见
how to use std::rel_ops to supply comparison operators automatically?
关于c++ - 元编程 C/C++ : how can I avoid using macros here?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31932307/