TITLE: example of traits usage (Newsgroups: comp.lang.c++.moderated, 12 Mar 2000) STUEKEN: Dieter Stueken > this is a simple function to copy a const array: > > const int *copy(const int *src, int len) > { > int *tmp = new int[len]; > for(int i=0; i tmp[i] = src[i]; > > return tmp; > } > > OK. looks fine. Now I want to turn it into a template: > > template T *copy(T src, int len) > > You will find, that tmp turns into const too > and cannot be initialized any more :-( > > The only solution I found is to define an other const_copy > template, to get hands on the non const T, like: > > template const T *const_copy(const T src, int len) > > Unfortunately I don't have just a tiny function but a huge > template class instead. So, do I have to copy the whole thing > again for the const case, or is there an other solution for that? ADLER: Darin Adler There's a solution with traits: template struct non_const_pointer; template struct non_const_pointer { typedef T* type; }; template struct non_const_pointer { typedef T* type; }; template typename non_const_pointer::type copy(T* src, int len) { typename non_const_pointer::type tmp = new T[len]; for (int i=0; i