如果匿名嵌套,则在其外部结构/类中。 (<- 添加到标题而不使其变长)。
我希望能够简单地调用一个函数并获取正在使用的 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/