c++ - recursive variadic template function call "loses" pointer on second argument type -
i've got function (getargs) using variadic template sorts through it's arguments (each pointer), sending each function (getarg) has been overloaded each type (at moment int & float). overloaded funtions each type set value @ pointer.
it compiles fine, , when call function many arguments of single type runs fine. if use 2 types (float & int), run fine until first occurrence of second type, crashing because (from can tell) pointer address null (0x0 in debugger).
here function definitions(declared in namespace included in main):
namespace.h
int getarg(int istackpos,int *i); int getarg(int istackpos,float *f); template<typename tfirst> int getargs(tfirst first) { getarg(-1,first); } template<typename tfirst, typename... trest> int getargs(tfirst first, trest... rest) { int istackpos = ((sizeof...(rest) + 1) * -1); getarg(istackpos,first); getargs((rest)...); return 0; }
namespace.cpp
int getarg(int istackpos,int *i) { *i = 1; } int getarg(int istackpos,float *f) { *f = 2.5; }
call args in main:
would run fine:
int *i1; float *f1; namespace::getargs(f1,f1,f1,f1); //no use of int
would crash:
int *i1; float *f1; namespace::getargs(f1,i1,f1); //use of int
the same true when int comes first , float after. null pointer happens in recursive getargs() call, , crash occurs because overloaded int getarg() tries write that. istackpos used position on lua stack, meant wrapper arguments lua. i've replaced lua code assigning int 1, float 2.5, lua code wasn't issue.
as others suggested, you're passing uninitialized memory function. produces undefined behavior.
also, you're not returning in getarg
functions , first getargs
. can trouble well.
and combining size_t , int when calculating istackpos.
Comments
Post a Comment