C++ (Qt)struct CData { enum Type { type_Value, type_Coord, type_Color }; Type m_type; union { double m_value; double m_coord[3]; float m_color[4]; };};
C++ (Qt)void DoSomething( const CData & src, CData & dst, int index ){... // хотелось бы записать такdst.Set(index, src[index]); // а еще лучше такdst[index] = src[index];}
C++ (Qt)void DoSomething( const CData & src, CData & dst, int index){ ... dst = src;}
C++ (Qt)???? operator[](int index){...}
C++ (Qt)#include <iostream>#include <array>#include <exception>#include <variant.hpp> typedef double value_t;typedef std::array<double, 3> coord_t;typedef std::array<float, 4> color_t;typedef boost::variant<value_t, coord_t, color_t> data_t; class my_visitor : public boost::static_visitor<value_t>{public: my_visitor(size_t index) : m_index(index) {} value_t operator()(const value_t & x) const { if (m_index != 0) throw std::out_of_range("out of range!"); return x; } template <class T> value_t operator()(const T & x) const { return x.at(m_index); } private: size_t m_index;}; struct CData{ data_t data; value_t operator[] (size_t index) const { return boost::apply_visitor(my_visitor(index), data); }}; int main(){ CData data1; CData data2; data1.data = 3.14; data2.data = color_t{.5f, .5f, .5f, .0f}; try { std::cout << data1[0] << std::endl; std::cout <<data2[3] << std::endl; } catch (const std::out_of_range & exc) { std::cout << exc.what() << std::endl; } return 0;}
C++ (Qt)#include <iostream>#include <array>#include <exception>#include <boost/any.hpp>#include <specmath/any_visitor/any_visitor.h> typedef double value_t;typedef std::array<double, 3> coord_t;typedef std::array<float, 4> color_t; class my_any_visitor : public any_visitor<value_t, type_list<value_t, coord_t, color_t>>{public: my_any_visitor(size_t index) : m_index(index) {} value_t operator()(const value_t & x) const { if (m_index != 0) throw std::out_of_range("out of range!"); return x; } template <class T> value_t operator()(const T & x) const { return x.at(m_index); } private: size_t m_index;}; struct CData{ boost::any data; value_t operator[] (size_t index) const { return apply_any_visitor(my_any_visitor(index), data); }}; int main(){ CData data1; CData data2; data1.data = 3.14; data2.data = color_t{.5f, .5f, .5f, .0f}; try { std::cout << data1[0] << std::endl; std::cout << data2[1] << std::endl; } catch (const std::out_of_range & exc) { std::cout << exc.what() << std::endl; } }
C++ (Qt)double CData::GetNth( size_t index ) const{ Q_ASSERT(index < size()); switch (m_type) { case type_Value: Q_ASSERT(index == 0); return m_value; case type_Coord: return m_coord[index]; case type_Color: return m_color[index]; default: Q_ASSERT(0); } return 0.0;}