c++ - Is this visitor implementation correct? -



c++ - Is this visitor implementation correct? -

i implementing visitor in order utilize boost variant library. want know if right specialize boost::static_visitor<> const reference type.

note question here following:

there problem specializing boost::static_visitor<> boost::static_visitor<const t&> ?

template<typename t> struct my_visitor : public boost::static_visitor<const t&> { template<typename u> const t& operator()(u& u) const { // code here ..... homecoming x<u>::get_some_t(); // homecoming t. } };

there no problem long don't homecoming reference local/temporary.

also, sure check validity of reference on time (it ends when variant object destructed, when variant destructed, or (!) when reinitialized).

background , explanation

a variant contains object of "current" element type, , can reference object fine. as long as variant not reinitialized element type (in case reference "just" dangling, if lifetime of referred-to object had ended).

so if get_somet_t() returns t& or t const& (or suitable implicit conversion) there no problem.

in simpler setting allow me demonstrate valid options:

variant<int, std::string> v1 = 42; int& i1 = get<int>(v1); // returns ref, valid i1 *= 2; // v1 contains updated integer value 84

likewise, can create variants of /just references/:

std::string s = "hello"; int reply = 42; variant<int&, std::string&> v2(s); get<std::string&>(v2) += " world"; // s contains "hello world" variant<int&, std::string&> v3(answer); get<int&>(v3) *= 2; // `answer` contains 84

see live on coliru

demonstration

put yet way, next fine:

struct { std::string a_property; }; struct b { std::string b_field; }; struct select_member : static_visitor<std::string&> { std::string& operator()(a& a) const { homecoming a.a_property; } std::string& operator()(b& b) const { homecoming b.b_field; } }; int main() { variant<a,b> v = { "some string" }; apply_visitor(select_member(), v) += " suffix"; std::cout << get<a>(v).a_property << "\n"; // prints "some string suffix" }

see live on coliru well.

c++ boost boost-variant static-visitor

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -