#Trying to push back structs/classes with std::variant
12 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
;compile -std=c++23
#include <iostream>
#include <vector>
#include <variant>
struct Main {
int a;
};
struct Bingo : Main {
int b;
};
using Things = std::variant<Bingo>;
int main() {
std::vector<Things> children;
Bingo bingo;
bingo.a = 5;
bingo.b = 8;
children.push_back(bingo);
std::cout << children[0].a << "\n";
std::cout << children[0].b << "\n";
}
Compiler Output
<source>: In function 'int main()':
<source>:21:28: error: '__gnu_cxx::__alloc_traits<std::allocator<std::variant<Bingo> >, std::variant<Bingo> >::value_type' {aka 'class std::variant<Bingo>'} has no member named 'a'
21 | std::cout << children[0].a << "\n";
| ^
<source>:22:28: error: '__gnu_cxx::__alloc_traits<std::allocator<std::variant<Bingo> >, std::variant<Bingo> >::value_type' {aka 'class std::variant<Bingo>'} has no member named 'b'
22 | std::cout << children[0].b << "\n";
| ^
Build failed
kojobailey | c++ | x86-64 gcc 13.2 | godbolt.org
(There's only one struct in the variant rn bc I haven't added more yet)
this is simply a test compilation
You need to use std::get to get the Bingo type from the variant
#include <iostream>
#include <variant>
#include <vector>
struct Main {
int a;
};
struct Bingo : Main {
int b;
};
using Things = std::variant<Bingo>;
int main() {
std::vector<Things> children;
Bingo bingo;
bingo.a = 5;
bingo.b = 8;
children.push_back(bingo);
std::cout << std::get<Bingo>(children[0]).a << "\n";
std::cout << std::get<Bingo>(children[0]).b << "\n";
}
aha
;compile -std=c++23
#include <iostream>
#include <vector>
#include <variant>
struct Main {
int a;
};
struct Bingo : Main {
int b;
};
using Things = std::variant<Bingo>;
int main() {
std::vector<Things> children;
Bingo bingo;
bingo.a = 5;
bingo.b = 8;
children.push_back(bingo);
std::cout << std::get<Bingo>(children[0]).a << "\n";
std::cout << std::get<Bingo>(children[0]).b << "\n";
}
Program Output
5
8
kojobailey | 96ms | c++ | x86-64 gcc 13.2 | godbolt.org
thank you