c++ - 使用其中的函数返回 union 的事件成员

标签 c++ c++14 unions

如果匿名嵌套,则在其外部结构/类中。 (<- 添加到标题而不使其变长)。

我希望能够简单地调用一个函数并获取正在使用的 union 成员(通过任何方式,例如返回它,修改参数等......),而不是类型(或类型的标识符) 但实际的成员,或指向它的非空指针。有没有办法在现代 (c++14) c++ 中做到这一点?

最佳答案

boost::variant ,当前值/类型被存储。您可以将 static_visitor 应用于变体,例如:

#include "boost/variant.hpp"
#include <iostream>

class times_two_visitor : public boost::static_visitor<>
{
public:

    void operator()(int & i) const
    {
        i *= 2;
    }

    void operator()(std::string & str) const
    {
        str += str;
    }
};


int main()
{
    boost::variant<int, std::string> u("hello world");
    std::cout << u; // output: hello world

    boost::apply_visitor(times_two_visitor(), u);
    std::cout << u; // output: hello worldhello world
    u = 21;
    boost::apply_visitor(times_two_visitor(), u);
    std::cout << u; // output: 42
}

关于c++ - 使用其中的函数返回 union 的事件成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34376406/

相关文章:

c++ - 有条件地构造参数包的默认可构造类

c++ - 如何将浮点值的字节存储在字符串中并随后检索该值?

c - 不同大小成员的 union 的内存布局?

c++ - 为什么在复制构造函数中分配 union 成员会崩溃?

c++ - 定义命名空间成员与无限定的自由函数

c++ - 打印链接列表

c++ - 创建动态 Cstring

c++ - Doxygen 文档注释#define

c++ - klee on c++14 程序

c++ - 如何读取未知数量的输入?