#Trying to push back structs/classes with std::variant

12 messages · Page 1 of 1 (latest)

oblique narwhal
#

Firstly, not sure why the below code isn't working:

frosty whaleBOT
#

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.

oblique narwhal
#

;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";
}
novel patioBOT
#
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
oblique narwhal
#

(There's only one struct in the variant rn bc I haven't added more yet)

#

this is simply a test compilation

rapid jungle
#

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";
}
oblique narwhal
#

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";
}
novel patioBOT
#
Program Output
5
8
oblique narwhal
#

thank you