i have following non-type template:
template<size_t max_size> struct path{ struct point{ float x; float y; } }; point segment[max_size]; };
if declare 2 different paths, cannot assign elements of different segments each other, structs may have same structure, of different type :
path<10> path_a ; path<30> path_b ; path_a.segment[0].x = 1; path_a.segment[0].y = 2; path_b.segment[0] = path_a.segment[0]; // <- error c2679 in visual studio)
of course, if separate definition of point , path, assignment work:
struct point{ float x; float y; }; template<size_t max_size> struct path{ point segment[max_size]; };
but that's not want (this mwe), wondering how can overload copy assignment operator make work. i've tried numerous variants, example:
template<size_t max_size> struct path{ struct point{ float x; float y; template<size_t other_size> point & operator = (const typename path<other_size>::point & that) { x = that.x; y = that.y; return *this; } }; point segment[max_size]; };
but same error. question is: possible overload = in way allows assignment of following form without changing layout of structs?
path_b.segment[0] = path_a.segment[0];
yes, such setup possible. @ core, need assignment operator template accept types:
template<class t> point & operator = (const t & that)
as basic solution, enough. work types have members x
, y
of compatible types, , produce (usually) ugly error message types don't.
if that's enough you, we're done.
if have other overloads of assignment operator, want selectively disable template one. this, need instrument point
classes , use sfinae:
template<size_t max_size> struct path{ struct point{ float x; float y; struct enableassignment {}; }; point segment[max_size]; };
the instrumentation used this:
template<class t, class u = typename t::enableassignment> point & operator = (const t & that)
the code above uses default template argument in function template, introduced in c++11. before that, have invoke sfinae in other way:
template <class l, class r> struct sfinaethenright { typedef r type; }; template <class t> typename sfinaethenright<typename t::enableassignment, point&>::type operator = (const t & that)
Comments
Post a Comment