Can a union in C++ have a member function? How do union with data members and member functions exist if an object is created?
If I suppose yes, then are they feasible an
The union
is a C-structure, and does not work well with C++ types (there are a number of caveats actually). However there already exist a C++ equivalent, which effectively work with all C++ classes and user-defined classes and is even safer than the union!
Behold Boost.Variant!
You can define a boost::variant
and it'll make sure:
And it even comes with the excellent: boost::static_visitor
which let's you apply a method on the union regardless of its type and provide compile-time checking to warn you whenever you have forgotten one of the possible types!
class MyVisitor: boost::static_visitor
{
public:
int operator()(std::string const& s) const {
return boost::lexical_cast(s);
}
int operator()(Foo const& f) const { return f.getAsInt(); }
int operator()(char c) const { return c; }
};
typedef boost::variant MyVariant;
int main(int argc, char* argv[]) {
MyVariant v; // the std::string is constructed
if (argc % 2) { v = Foo(4); }
if (argc % 3) { v = argv[1][0]; }
if (argc % 5) { v = argv[1]; }
std::cout << boost::apply_visitor(MyVisitor(), v) << '\n';
return 0;
}
Also... it's as efficient (fast) as a union
, and does not involve any dynamic look-up like Boost.Any would.