在相同类型的字段上迭代
Iterating over fields of the same type
让您有以下类:
class Data
{
public:
int a;
int b;
};
class DataOther
{
public:
int a;
int b;
};
class Line
{
public:
Data Right;
Data Left;
};
class LineOther
{
public:
DataOther Right;
DataOther Left;
}
我有很多这样的课程,当我想在数据的两个"侧面"上运行代码时,我通常会做这样的事情:
enum class Side { RIGHT, LEFT };
template<typename T>
auto GetBySide(const Side &side, T &data) -> decltype(data.Right) &
{
return side == Side::Left ? data.Left : data.Right;
}
,然后在代码中:
Line l;
LineOther lOther;
for(auto &side: {Sides::LEFT, Sides::Right})
{
auto &d = GetBySide(side, l);
auto &dOther = GetBySide(side, lOther);
// Do some stuff with the data
}
现在的下一侧是它是运行时的,因此无法进行太多的优化,尽管我想编译器可能会展开循环。
关于如何构建代码的其他想法?
如果您担心展开,则可以替换:
Line l;
LineOther lOther;
for (auto &side: {Sides::LEFT, Sides::Right})
{
auto &d = GetBySide(side, l);
auto &dOther = GetBySide(side, lOther);
// Do some stuff with the data
}
诸如:
之类的东西template <Side side>
void foo(Line& l, LineOther& lOther) {
auto &d = GetBySide(side, l);
auto &dOther = GetBySide(side, lOther);
// Do some stuff with the data
}
和
Line l;
LineOther lOther;
foo<Sides::LEFT>(l, lOther);
foo<Sides::Right>(l, lOther);
"我有很多这样的类,"似乎您只能留下其中一个。或至少利用继承或其他技术来避免重复:
// Declare base class instead of copypasting fields.
class BaseLine
{
public:
int Right{};
int Left{};
};
class Line: public BaseLine
{};
class LineOther: public BaseLine
{};
int main()
{
Line l;
l.Right = 45; l.Left = 89;
LineOther lOther;
lOther.Right = 74; lOther.Left = 33;
// Use pointer to member to iterate over fields.
for(auto p_side: {&BaseLine::Right, &BaseLine::Left})
{
::std::cout << (l.*p_side) << ::std::endl;
::std::cout << (lOther.*p_side) << ::std::endl;
}
}
在线编译器
相关文章:
- 如何使用迭代器初始化地图的键字段?
- 您可以在一段时间内迭代向量
- 在相同类型的字段上迭代
- C 模板功能在任何集合成员字段上迭代
- 为什么从工厂函数分配向量并在循环中迭代它会导致段错误
- python+libclang;来回迭代:将字段注释绑定到字段
- 将迭代器映射到特定字段上的迭代器(可以使用 Boost)
- 在编译时使用模板在跨结构字段中迭代
- 段错误:使用迭代器的插入函数
- 正在取消引用自定义结构字段的迭代器
- 使用C预处理器在结构字段上进行迭代
- C++使用boost-fusion-adapt_struct迭代到嵌套结构字段中
- 如何在容器项的字段上创建迭代器?
- 在 65536 位置访问迭代器的指针运算符会导致段错误
- 取消引用的列表迭代器段错误
- 任务在删除其中一个迭代对象时会导致段错误
- C++ 如何在结构向量的一个字段上创建迭代器
- C++ std::vector<std::string> 迭代器段错误
- GDB Python脚本:通过C/C++结构字段迭代的任何示例
- 从任何结构或元组按字符串形式的字段键获取迭代器