访问 std::variant 中的公共结构成员 [英] Accessing common struct members in std::variant
本文介绍了访问 std::variant 中的公共结构成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法理解如何在 C++17 中使用 std::variant
.给定两个结构体 A
和 B
,以及一个 std::vector
,我想:
I have trouble understanding how to use std::variant
in C++17. Given two struct A
and B
, and a std::vector<std::variant<A,B>> vs
, I would like to:
- 引用一个通用的结构体成员,例如
n
; - 调用一个通用函数,例如
fun()
或add()
.
#include <iostream>
#include <variant>
#include <vector>
struct A {
int n;
void fun() { std::cout << "fun\n"; }
int add(int m) { return n+m; }
};
struct B {
int n;
void fun() { std::cout << "fun\n"; }
int add(int m) { return n+m; }
};
int main() {
std::vector<std::variant<A,B>> vs;
vs.push_back(A{10,11});
vs.push_back(B{20,22});
// How to refer to struct members without using std::get<v.index()>(v)?
for (auto && v : vs) {
// 1. How to refer to v.n?
// 2. How to call v.fun()?
// 3. How to call v.add() with input parameter m?
}
}
有人告诉我使用 std::visit
,但我太直率而无法理解它是如何工作的.有人可以在这里展示一个简单的例子吗?
I am told to use std::visit
, but am too blunt to understand how it works. Could anyone show a simple example here?
推荐答案
使用带有 auto&&
参数的 lambda 的 std::visit
来访问成员对所有变体类型都是通用的.在您的示例中:
Use std::visit
with a lambda that has an auto&&
parameter to access members that are common to all variant types. In your example:
for (auto&& v : vs) {
std::visit([&](auto&& x){
std::cout << x.n << x.add(1);
x.fun();
}, v);
}
这篇关于访问 std::variant 中的公共结构成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文