相关疑难解决方法(0)

访问 std::variant 中的公共结构成员

我无法理解如何std::variant在 C++17 中使用。给定两个 struct AandB和 a 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 …
Run Code Online (Sandbox Code Playgroud)

c++ struct variant c++17

3
推荐指数
1
解决办法
353
查看次数

标签 统计

c++ ×1

c++17 ×1

struct ×1

variant ×1