为同一类提供不同比较运算符的最佳策略是什么?
What's the best strategy to provide different comparison operators for the same class?
考虑这个简单的类存储一个值和时间。
class A
{
public:
boost::posix_time::ptime when;
double value;
};
根据上下文,我需要按值或时间比较A
的两个实例(和/或将它们存储在 set
/map
中,有时按值排序,有时按时间按时间进行排序)。
提供operator<
会令人困惑,因为您无法确定它是否会按值进行比较或按时间进行比较。
现在,最好的策略是什么?
- 是否可以提供
operator<
采用参数?(将用作a <(ByTime) b
)? - 我是否应该有一个
lowerThan
(比较值)方法和earlierThan
(比较时间)方法将正确的操作数作为参数?但是,处理<
,<=
,>
,>=
,==
,!=
的最佳做法是什么?或者他们可能采用参数(例如bool isLower(bool strict, const A& right) const
,bool isGreater(bool strict, const A& right) const
,bool isEarlier(bool strict, const A& right) const
,bool isLater(bool strict, const A& right) const
...
最好的做法是什么?
imho最通用的方式是一个2步流程:
-
制作adl getters。
-
用那些getters来写比较概念。
示例:
#include <boost/date_time.hpp>
#include <set>
#include <vector>
#include <algorithm>
class A
{
public:
boost::posix_time::ptime when;
double value;
};
// get the 'when' from an A
auto get_when(A const& a) -> boost::posix_time::ptime
{
return a.when;
}
// get the 'when' from a ptime (you could put this in the boost::posix_time namespace for easy ADL
auto get_when(boost::posix_time::ptime t) -> boost::posix_time::ptime
{
return t;
}
// same for the concept of a 'value'
auto get_value(A const& a) -> double
{
return a.value;
}
auto get_value(double t) -> double
{
return t;
}
// compare any two objects by calling get_when() on them
struct increasing_when
{
template<class L, class R>
bool operator()(L&& l, R&& r) const
{
return get_when(l) < get_when(r);
}
};
// compare any two objects by calling get_value() on them
struct increasing_value
{
template<class L, class R>
bool operator()(L&& l, R&& r) const
{
return get_value(l) < get_value(r);
}
};
void example1(std::vector<A>& as)
{
// sort by increasing when
std::sort(begin(as), end(as), increasing_when());
// sort by increasing value
std::sort(begin(as), end(as), increasing_value());
}
int main()
{
// same for associative collections
std::set<A, increasing_when> a1;
std::set<A, increasing_value> a2;
}
更新:
如果愿意,可以对比较进行模板:
template<class Comp>
struct compare_when
{
template<class L, class R>
bool operator()(L&& l, R&& r) const
{
return comp(get_when(l), get_when(r));
}
Comp comp;
};
using increasing_when = compare_when<std::less<>>;
using decreasing_when = compare_when<std::greater<>>;
直接使用代码中的比较:
auto comp = compare_when<std::greater<>>();
if (comp(x,y)) { ... }
对ukmonkey的评论做出反应,定义我所理解的"比较类别"是一种好方法/练习?
class A
{
public:
boost::posix_time::ptime when;
double value;
const boost::posix_time::ptime& getTime() const { return when; }
double getValue() const { return value; }
};
template <typename T>
class CompareBy
{
public:
CompareBy( const A& a, T (A::*getter)() const ) : a(a), getter(getter)
{}
bool operator<( const CompareBy& right ) const
{
return (a.*getter)() < (right.a.*getter)();
}
// you may also declare >, <=, >=, ==, != operators here
private:
const A& a;
T (A::*getter)() const;
};
class CompareByTime : public CompareBy<const boost::posix_time::ptime&>
{
public:
CompareByTime(const A& a) : CompareBy(a, &A::getTime)
{
}
};
class CompareByValue : public CompareBy<double>
{
public:
CompareByValue( const A& a ) : CompareBy(a, &A::getValue)
{
}
};
struct byTime_compare {
bool operator() (const A& lhs, const A& rhs) const {
return CompareByTime(lhs) < CompareByTime(rhs);
}
};
int main()
{
A a, b;
...
if (CompareByValue(a) < CompareByValue(b))
{
...
}
std::set<A, byTime_compare> mySet;
}
简短答案:不要我解释了为什么在评论中,主要原因是,它引入了您的代码中的歧义并降低了可读性,这与操作员的意图相反。只需使用不同的方法,并提供选择用于此类的方法(例如比较)。当我键入此内容时,人们发布了很好的例子,即使有些则使用一些元编程。
但是,对于科学,您可以。虽然您无法向操作员添加参数(二进制运算符是二进制运算符,并且似乎没有语法可以在某处添加第三个参数),您可以使操作员在不同的上下文中表示不同的内容(C 上下文,对于" {}"')划定的代码行或块
在这里使用施工/破坏顺序很快完成(与琐碎的锁相似,而无需考虑线程安全):
比较看起来像:
Thing::thingSortingMode(Thing::thingSortingMode::alternateMode), Thing{1, 2} < Thing{3, 4};
在线运行此示例:http://cpp.sh/3ggrq
#include <iostream>
struct Thing {
struct thingSortingMode {
enum mode {
defaultMode,
alternateMode
};
mode myLastMode;
thingSortingMode(mode aMode) { myLastMode = Thing::ourSortingMode; Thing::ourSortingMode = aMode; std::cout << "nmode: " << aMode << "n"; }
~thingSortingMode() { Thing::ourSortingMode = myLastMode; std::cout << "nmode: " << myLastMode << "n";}
};
bool operator < (Thing another) {
switch (ourSortingMode) //I use an enum, to make the example more accessible, you can use a functor instead if you want
{
case thingSortingMode::alternateMode:
return myValueB < another.myValueB;
break;
default:
return myValueA < another.myValueA;
break;
}
}
static thingSortingMode::mode ourSortingMode;
int myValueA;
int myValueB;
};
Thing::thingSortingMode::mode Thing::ourSortingMode = Thing::thingSortingMode::defaultMode;
int main()
{
Thing a{1, 1}, b{0, 2}; // b < a in default mode, a < b in alternate mode
std::cout << (a < b); //false
{
Thing::thingSortingMode ctx(Thing::thingSortingMode::alternateMode);
std::cout << (a < b); //true
Thing::thingSortingMode(Thing::thingSortingMode::defaultMode), std::cout << (a < b), //false
Thing::thingSortingMode(Thing::thingSortingMode::alternateMode), std::cout << (a < b); //true
std::cout << (a < b); //true
}
std::cout << (a < b); //false
}
请注意,这种构建/破坏技巧可以管理任何类型的上下文状态,这是一个更丰富的例子,具有4个状态和更多嵌套上下文
在线运行此示例:http://cpp.sh/2x5rj
#include <iostream>
struct Thing {
struct thingSortingMode {
enum mode {
defaultMode = 1,
alternateMode,
mode3,
mode4,
};
mode myLastMode;
thingSortingMode(mode aMode) { myLastMode = Thing::ourSortingMode; Thing::ourSortingMode = aMode; std::cout << "nmode: " << myLastMode << " -> " << aMode << "n"; }
~thingSortingMode() { std::cout << "nmode: " << Thing::ourSortingMode << " -> " << myLastMode << "n"; Thing::ourSortingMode = myLastMode; }
};
static thingSortingMode::mode ourSortingMode;
};
Thing::thingSortingMode::mode Thing::ourSortingMode = Thing::thingSortingMode::defaultMode;
int main()
{
Thing::thingSortingMode ctx(Thing::thingSortingMode::mode3);
{
Thing::thingSortingMode ctx(Thing::thingSortingMode::alternateMode);
{
Thing::thingSortingMode ctx(Thing::thingSortingMode::mode4);
{
Thing::thingSortingMode ctx(Thing::thingSortingMode::defaultMode);
std::cout << "end sub 3 (mode 1)n";
}
std::cout <<
(Thing::thingSortingMode(Thing::thingSortingMode::alternateMode), "this is the kind of things that might behave strangelyn") <<
(Thing::thingSortingMode(Thing::thingSortingMode::defaultMode), "here both are printed in mode 2, but it's a direct consequence of the order in which this expression is evaluatedn"); //note though that arguments are still constructed in the right state
std::cout << "end sub 2 (mode 4). Not that we still pop our states in the right order, even if we screwed up the previous linen";
}
std::cout <<
(Thing::thingSortingMode(Thing::thingSortingMode::alternateMode), "this on the other hand (mode 2)n"),
std::cout <<
(Thing::thingSortingMode(Thing::thingSortingMode::defaultMode), "works (mode 1)n"); //but pay attention to the comma and in which order things are deleted
std::cout << "end sub 1 (mode 2)n";
}
std::cout << "end main (mode 3)n";
}
输出:
mode: 1 -> 3
mode: 3 -> 2
mode: 2 -> 4
mode: 4 -> 1
end sub 3 (mode 1)
mode: 1 -> 4
mode: 4 -> 1
mode: 1 -> 2
this is the kind of things that might behave strangely
here both are printed in mode 2, but it's a direct consequence of the order in which this expression is evaluated
mode: 2 -> 1
mode: 1 -> 4
end sub 2 (mode 4). Not that we still pop our states in the right order, even if we screwed up the previous line
mode: 4 -> 2
mode: 2 -> 2
this on the other hand (mode 2)
mode: 2 -> 1
works (mode 1)
mode: 1 -> 2
mode: 2 -> 2
end sub 1 (mode 2)
mode: 2 -> 3
end main (mode 3)
mode: 3 -> 1
另一种方法,非常简单:添加模板比较器函数在A类中可以轻松进行比较,并且确实很容易出错:
#include <iostream>
#include <set>
using namespace std;
class A
{
public:
int when;
double value;
int getTime() const { return when; }
double getValue() const { return value; }
template<typename T>
bool isLower( T (A::*getter)() const,
bool strict,
const A& right ) const
{
if ( strict )
return ((*this).*getter)() < (right.*getter)();
else
return ((*this).*getter)() <= (right.*getter)();
}
template<typename T>
bool isGreater( T (A::*getter)() const,
bool strict,
const A& right ) const
{
if ( strict )
return ((*this).*getter)() > (right.*getter)();
else
return ((*this).*getter)() >= (right.*getter)();
}
template<typename T>
bool isEqual( T (A::*getter)() const,
const A& right ) const
{
return ((*this).*getter)() == (right.*getter)();
}
};
struct byTime_compare {
bool operator() (const A& lhs, const A& rhs) const {
return lhs.isLower( &A::getTime, true, rhs );
}
};
int main()
{
A a, b;
if ( a.isLower( &A::getValue, true, b ) ) // means a < b by value
{
// ...
}
std::set<A, byTime_compare> mySet;
}
- 为什么比较运算符如此快速
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 关于 std::min, std::max 中的比较运算符的混淆
- 三向比较运算符成员与非成员实现
- 标准::可选枚举的比较运算符
- 为什么字符串比较的 == 运算符相对于任一字符串长度线性时间(似乎)?
- C++分数混合比较运算符错误
- <<运算符优先级与字符串比较
- 不能将重载比较运算符与 Catch 测试一起使用
- 重构使用动态强制转换的 std::set 的比较运算符
- ">"运算符和"<"运算符如何进行字符串比较?
- "operator()"在重载运算符方法中是什么意思,在priority_queue(STL)中用作C++中的比较器?
- C++使用关系运算符比较字符串
- 为什么使用 and 运算符比较 if 语句中的 2 个对象会抛出错误,而使用 2 if 语句则不会
- 使用关系运算符比较指针意味着什么
- 运算符<比较多个字段
- 运算符==比较两个不同的类
- 使用==运算符比较字符串到0
- 使用'if'语句和"<<"时的结果错误,'>>'运算符比较 3 个整数