Wednesday 15 January 2014

c++ - Getting the type of a variable in a template -



c++ - Getting the type of a variable in a template -

this spawned trying extract type unique_ptr, turned out easy. however, interested in general case.

here's looking for:

template<class childobj> void mychildfunc() { // stuff childobj type }; template<class objtype> void myfunc(objtype obj) { mychildfunc<type of objtype::child????>(); }; struct myintstruct { int child; }; struct mydoublestruct { double child; }; void main(void) { myintstruct int_struct; mydoublestruct double_struct; myfunc(int_struct); myfunc(double_struct); }

so want way of calling mychildfunc using type of attribute object passed in myfunc. know can create template function, , pass obj.child allow deduction, hoping way deduce type manually, , utilize in template argument directly.

as said, more academic real, why code contrived, interested know if there way it.

how's this:

template<class childobj> void mychildfunc() { // stuff childobj type }; template<class objtype> void myfunc(objtype obj) { mychildfunc<decltype(objtype::child) >(); }; struct myintstruct { int child; }; struct mydoublestruct { double child; }; int main(int argc, const char * argv[]) { myintstruct int_struct; mydoublestruct double_struct; myfunc(int_struct); myfunc(double_struct); homecoming 0; }

i compiled xcode 6 , seems work desired.

c++ templates

No comments:

Post a Comment