c++ - Template class constructor not working -
from other question here copying std container frm arbitrary source object managed template working under msvc. unfortunately compiler crashes newest addtion of adding constructor accept kind of std containers, , real project in gcc anyway. when use template in gcc, several errors don't know how resolve.
template <class t> class readonlyiterator { public: template <typename v, typename u> struct is_same { enum { value = 0 }; }; template <typename v> struct is_same<v, v> { enum { value = 1 }; }; template <bool, typename> struct enable_if {}; template <typename v> struct enable_if<true, v> { typedef v type; }; template <typename container> typename enable_if< is_same<t, typename container::value_type>::value, readonlyiterator<t>&>::type operator= (const container &v) { return *this; } template <typename container> readonlyiterator(const container &v, typename enable_if<is_same<t, typename container::value_type>::value, void>::type * = 0) { mvector = v; mbegin = mvector.begin(); } };
my goal allow assignments this:
std::vector<simpleclass *>v; std::list<simpleclass *>l; readonlyiterator<simpleclass *> t0 = v; readonlyiterator<simpleclass *> &t1 = v; readonlyiterator<simpleclass *> t2 = readonlyiterator<simpleclass *>(v); readonlyiterator<simpleclass *> t3 = l; t0 = v; t0 = l;
i updated code above , reverted wrong changes applied. original problem tried fix:
readonlyiterator<simpleclass *> &t1 = v;
leads to:
invalid initialization of reference of type 'readonlyiterator<simpleclass*>&' expression of type 'std::vector<simpleclass*, std::allocator<simpleclass*> >'
as found out, if write template class within template class, have give template parameters different names:
template <typename u, typename v> struct is_same<u, v> { enum { value = 0 }; };
in specialization of is_same
, have use same types when specifying specialized class name (you can name u
, use same name on 3 places: in template parameter list in specialized class name):
template <typename v> struct is_same<v, v> { enum { value = 1 }; };
also, mentioned in comments, should make these helper-classes struct
instead of class
; don't have write public:
.
Comments
Post a Comment