ฉันมีปัญหาในการทำความเข้าใจวิธีใช้ std::variant
ใน C ++ 17 เมื่อพิจารณาสองโครงสร้าง A
และ B
และ std::vector<std::variant<A,B>> vs
ฉันต้องการ:
- อ้างถึงสมาชิกโครงสร้างทั่วไปเช่น
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
แต่ฉันตรงไปตรงมาเกินกว่าจะเข้าใจวิธีการทำงาน ใครช่วยแสดงตัวอย่างง่ายๆ ที่นี่ได้ไหม