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:
- Refer to a common struct member, e.g.
n
; - Call a common function, e.g.
fun()
oradd()
.
#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?
}
}
I am told to use std::visit
, but am too blunt to understand how it works. Could anyone show a simple example here?