类似于Preferred implementation of '<' for multi-variable structures,我为具有多个值的结构实现了一个小于操作符。我并不担心使用相等或小于运算符,让我们假设所有成员都正确地实现了这两者。我的结构有四个字段,操作符已经变得非常混乱:
struct Key {
std::string s_name;
bool b_mipmaps;
bool b_clamp_to_edge;
GLenum n_intformat;
// [constructors here]
bool operator <(const Key &other) const
{
return s_name < other.s_name || (s_name == other.s_name && (
b_mipmaps < other.b_mipmaps || (b_mipmaps == other.b_mipmaps && (
b_clamp_to_edge < other.b_clamp_to_edge || (b_clamp_to_edge == other.b_clamp_to_edge && (
n_intformat < other.n_intformat))))));
// compare two keys
}
}我想知道是否有一种常用的缩进样式,或者某种东西可以帮助您避免在括号中迷路,因为坦率地说,这是地狱,我认为这样的操作符中的bug会很微妙,很难跟踪/调试。是否有一种方法可以将其分解为一些原始函数?或者有一个STL函数可以做到这一点?
我目前正在使用C++03,但我对更新的标准持开放态度。
发布于 2015-05-22 16:07:43
您可以使用std::tie:
bool operator <(const Key &other) const
{
return std::tie(s_name, b_mipmaps, b_clamp_to_edge, n_intformat) <
std::tie(other.s_name, other.b_mipmaps, other.b_clamp_to_edge, other.n_intformat);
}别忘了#include <tuple>
发布于 2015-05-22 15:59:36
您可以使用几个if。
bool operator <(const Key &other) const
{
if (s_name != other.s_name) return s_name < other.s_name;
if (!b_mipmaps && other.b_mipmaps) return true;
if (b_mipmaps && !other.b_mipmaps) return false;
if (!b_clamp_to_edge && other.b_clamp_to_edge) return true;
if (b_clamp_to_edge && !other.b_clamp_to_edge) return false;
return n_intformat < other.n_intformat;
// compare two keys
}发布于 2015-05-22 16:05:05
由于不知道代码中变量的类型,我发现使用变量名很难提出建议。
从您的代码中,不清楚操作符的语义应该是什么
(this->b_mipmaps && other.b_mipmaps)是true。
我使用以下模式:
bool operator <(const Key &other) const
{
if ( this->member1 != other.member1 )
{
return (this->member1 < other.member1);
}
if ( this->member2 != other.member2 )
{
return (this->member2 < other.member2);
}
//
// ...
//
return (this->memberN < other.memberN);
}编辑
现在我知道b_mipmaps是bool类型了,您可以使用:
if ( this->b_mipmaps != other.b_mipmaps )
{
return (this->b_mipmaps < other.b_mipmaps);
}或
if ( this->b_mipmaps != other.b_mipmaps )
{
return (!(this->b_mipmaps) && other.b_mipmaps);
}使用您发现更易读的样式。我觉得第一种形式更易读。
https://stackoverflow.com/questions/30401089
复制相似问题