c++ - 有没有办法存储多种类型的结构成员指针
问题描述
我有这段代码可以很好地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
,那将起作用。事实上,这段代码确实可以编译但会崩溃。
有什么解决办法吗?
解决方案
您可能会使用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;
推荐阅读
- html - 如何创建响应式客户徽标库
- laravel - Laravel-Vue 组件
- spring-boot - 如何在 Spring 中将可分页对象与自定义查询一起使用
- c# - 从 C# 运行 orientdb 服务器
- plugins - 使用 Telegraf 和 InfluxDB 的 Modbus TCP 连接被拒绝
- sql - SQL:如何将具有值的多个日期行(年、一月、二月、三月、...、十二月)转换为日期和值列?
- azure - Elastic Search - 文档文本搜索
- angular - Internet Explorer 11 中的 Angular 9 应用程序白屏和空控制台
- visual-studio-2015 - VS2015 诊断工具窗口不工作
- python - 程序在“if”方法中看不到对象