【问题标题】:get an iterator from any struct or tuple by key of a field as string通过字段的键作为字符串从任何结构或元组中获取迭代器
【发布时间】:2013-01-13 16:15:21
【问题描述】:

你知道 boost、poco 中的一个库,它有一个带有签名的函数,例如:

template <typename T> auto vectorize(const std::vector<std::string> & mask, T & t) -> T::iterator

可以这样使用:

struct A {double x; double y; double z;};
auto a = A();
auto it = vectorize({"x","z"}, a);
//and here doing perturbations and increments on a; ideally it is for passing it to another function

我正在重新设计执行此类操作的现有代码(使用在结构内部进行序列化的方法),但我不得不承认我们的版本相当混乱:/

您对此有抽象的想法并使用元组吗? 我目前正在尝试使用枚举来映射元组的字段。

我很确定有人为这种自反容器迭代问题写了一些聪明的东西。 (我希望 boost::fusion 但它只按类型过滤,否则我错过了一个页面)

【问题讨论】:

  • 您必须按原样使用struct A 吗?包含的类型是否总是统一的,例如所有双精度类型?
  • 目前我按原样使用struct A 加上serialize() 函数作为成员。为了提供一些背景知识,我有一个与boost::numeric::odeint 非常相似的库,并且某些算法必须能够操纵我系统的子状态,就像它是一个向量一样。目前我主要只有double 或std::vector&lt;double&gt;(可能某些用户有特定需求),但我想使用boost::unit 或带有constexpr 的单元作为其演示文稿中显示的Stroustrup。

标签: c++ boost struct iterator tuples


【解决方案1】:

C++ 没有任何神奇的方法可以像许多 VM 语言那样很好地做到这一点。

通常你会使用boost serialization 之类的东西。目标是您只需编写一个简单的映射函数,其余的只是配置策略。

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

class gps_position
{
public:
    int degrees;
    int minutes;
    float seconds;
    gps_position(){};
    gps_position(int d, int m, float s) :
        degrees(d), minutes(m), seconds(s)
    {}
};

namespace boost {
namespace serialization {

template<class Archive>
void serialize(Archive & ar, gps_position & g, const unsigned int version)
{
    ar & g.degrees;
    ar & g.minutes;
    ar & g.seconds;
}

} // namespace serialization
} // namespace boost

或者,如果您不使用 c++11,假设您总是序列化双精度或为 std::tuple 或 boost::tuple 编写静态访问者,您可能会获得一些牵引力。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    相关资源
    最近更新 更多