首页 > 解决方案 > 有没有办法存储多种类型的结构成员指针

问题描述

我有这段代码可以很好地foo按索引检索成员。

#include <string>
#include <iostream>

struct Foo {
    int a = 42;
    int b = 16;
    std::string str = "hi";
};

int main()
{
    int Foo::*members[] = { &Foo::a, &Foo::b };
    Foo foo;

    std::cout << foo.*members[1] << std::endl;
    return 0;
}

问题是我的std::string结构上有一个我希望能够以相同方式访问的结构,是否有可扩展到任何类型的解决方案?

我试过的:

#include <string>
#include <iostream>
#include <any>

struct Foo {
    int a = 42;
    int b = 16;
    std::string str = "coucou";
};

int main()
{
    std::any Foo::*members[] = { (std::any Foo::*)&Foo::a, (std::any Foo::*)&Foo::b, (std::any Foo::*)&Foo::str };
    Foo foo;

    std::cout << std::any_cast<int>(foo.*members[0]) << std::endl;
    return 0;
}

我告诉自己,如果存储一个数组std::any,那将起作用。事实上,这段代码确实可以编译但会崩溃。

有什么解决办法吗?

标签: c++pointersstruct

解决方案


您可能会使用std::tuple

std::tuple members{&Foo::a, &Foo::b, &Foo::str }; // C++17 CTAD
                                                  // else, use `std::make_tuple`
Foo foo;

std::cout << foo.*std::get<0>(members) << " " << foo.*std::get<2>(members) << std::endl;

演示


推荐阅读