如何不迷失在执行'<'对于多变量结构
How not to get lost in 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
}
}
我想知道是否有一种常用的缩进风格或一些东西可以帮助你不要迷失在括号中,因为坦率地说,它是地狱,我想这样一个操作符中的错误将是相当微妙的,很难追踪/调试。有没有办法把它分解成一些基本的函数?或者有一个STL函数可以做到这一点?
我目前使用的是c++ 03,但我对新标准持开放态度。
您可以使用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>
您可以使用几个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
}
不知道代码中变量的类型,我发现很难使用变量名来建议一些事情。
从您的代码中,不清楚操作符的语义应该是什么,如果
(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);
}
选择你觉得更容易读懂的样式。
关于@lisyarus的回答很好,但避免了重复字段名:
bool operator <(const Key &other) const
{
auto fields = [](decltype(*this) v) {
return std::tie(v.s_name, v.b_mipmaps, v.b_clamp_to_edge, v.n_intformat);
};
return (fields(*this) < fields(rhs));
}
相关文章:
- gsl多变量数值积分
- 数组变量中更多变量或更多维度?
- 如何将类成员专用于多个模板值(常量)?
- 不稳定的C :每行适应性变化多变量初始化
- 测试适用于成员变量的成员函数
- 标题中可以有太多变量吗?
- 多变量初始化编译器支持
- 适用于会员变量的新位置
- 如何将概念应用于成员变量
- 具有 std::enable_if 的多变量模板专用化
- GPU cuda 代码是否适用于多个 GPU 卡而无需任何实现
- 单行多变量声明的clang ast访问者
- 在 c++ 中将 txt 文件读入多变量维数组
- 一个包含多个OpenCL内核的程序相对于多个分别包含一个内核的程序的优势
- 什么是适用于多个入口和多个出口的类似BFS的最佳路径算法
- 映射多变量/层系统的泛化
- 对其中一个变量的多变量结构进行排序
- C++ 奇怪的情况,例如将现有变量应用于新变量
- 关键部分对象如何精确地适用于多个方法
- STL算法(如for_each)应用于多个参数