G'day all. On Feb 10, 2008 3:40 PM, Mattes Simeon <simeon.mattes@gmail.com> wrote:
Though in comparison with C or C++ I can't figure out so clear the syntax.
Quoting Victor Nazarov <asviraspossible@gmail.com>:
I think this is the most native way to do it in C++:
Herb Sutter and Andrei Alexandrescu will find you and beat you up if you write this. This is considered more appropriate. (Warning: untested code follows.) #include <boost/variant.hpp> template<typename A, typename B> class Tuple : public boost::variant<A, std::pair<A,B> > { private: typedef std::pair<A,B> pair_type; typedef boost::variant<A, pair_type> base_type; struct visitor_A : public boost::static_visitor<const A*> { const A* operator()(const A& a) { return &a; } const A* operator()(const pair_type& p) { return &p.first; } }; public: Tuple(const A& a) : base_type(a) { } Tuple(const A& a, const B& b) : base_type(pair_type(a,b)) { } const A* tuple1() const { return boost::apply_visitor(visitor_A(), *this); } const B* tuple2() const { const pair_type* p = boost::get<pair_type>(*this); return p ? &p->second : 0; } }; But in this specific case, this might be more appropriate: template<typename A,typename B> class Tuple { A m_a; boost::optional<B> m_b; // etc }; Cheers, Andrew Bromage