c++ - 如何通过字符串名称访问struct属性?

标签 c++ c++11 vector

我有一个结构:

typedef struct Tick {
    double open;
    double high;
    double low;
    double close;
    double ema100;
} Tick;

我想访问一个给定键的属性:
Tick currentTick = {44.5, 45.1, 44.2, 44.6, 44.255};
std::string key = "ema100";

std::cout << currentTick[key];

有没有不使用std::map的方法?我想答案是否定的,但是我只想确定在修改所有内容以使用std::map并增加内存需求之前。

最佳答案

Is there a way to do this without using std::map?



只要您愿意使用一系列层叠的if-else语句,就可以做到。

我会质疑设计。

您可以使用基于标签的成员变量部分地到达那里。 Sample working example:
#include <iostream>

struct OpenTag {};
struct HighTag {};
struct LowTag {};
struct CloseTag {};
struct Ema100Tag {};

struct Tick {

   template <typename Tag> struct Member
   {
      double val;

      operator double () const { return val; }

      operator double& () { return val; }
   };

   struct AllMembers : Member<OpenTag>, 
                       Member<HighTag>,
                       Member<LowTag>,
                       Member<CloseTag>,
                       Member<Ema100Tag> {};

   AllMembers data;

   template <typename Tag>
      double operator[](Tag t) const
      {
         return (Member<Tag> const&)(data);
      }

   template <typename Tag>
      double& operator[](Tag t)
      {
         return (Member<Tag>&)(data);
      }

};
int main()
{
   Tick t;
   t[OpenTag()] = 12.345;
   std::cout << t[OpenTag()] << std::endl;
}

输出:
12.345

关于c++ - 如何通过字符串名称访问struct属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36506588/

相关文章:

c++ - 使用带有 std::shared_ptr 的 Qt 对象

c++ - 编译时等效于 std::accumulate()

c++ - Eigen::aligned_allocator 因 std::unordered_multimap 而失败

VB.NET "For each"与 ".GetUpperBound(0)"

c++ - 使用 find() 在 vector 中查找元素

java - 是否有人仍在使用 Vector(而不是 Collections.synchronizedList(List list)/CopyOnWriteArrayList)?

c++ - Winapi 对话框在 Windows XP 上损坏

c++ - char*与char[]的区别(二)

c++ - g++ -fdump-class-hierarchy 的输出中的第一个 (int (*)(...))0 vtable 条目是什么?

c++ - 将 unique_ptr 插入 map ,指针被销毁