Pass generic type in c++ method as parameter -
i trying implement c++ method , want pass generic parameter in it. want assign parameter object's property. here example:
class myclass { public: unsigned long long var1; unsigned short var2; signed short var3; }
now have global object of myclass in someotherclass , method says:
void someotherclass::updatemyclassvalue(int paramtype, <generic> value) { switch(paramtype) { case1: objmyclass.var1 = value; case2: objmyclass.var2 = value; case3: objmyclass.var3 = value; } }
how pass such type, because if use fixed type e.g unsigned long long
parameter type, won't able assign var2 & var3. don't want loose data, e.g signed data may have -ve value.
please me overcome situation, have no experience working in c++. not sure if can achieve using templete<> in c++, if yes how?
thanks
pass parameter pointer:
void someotherclass::updatemyclassvalue(int paramtype, void* pvalue) { switch(paramtype) { case1: objmyclass.var1 = *(unsigned long long*)pvalue; case2: objmyclass.var2 = *(unsigned short)pvalue; case3: objmyclass.var3 = *(signed short)pvalue; }
this of course not type-safe , can lot of trouble when accidentally specify wrong paramtype. if use member template function instead, can let compiler checking you, example:
template<type t> void someotherclass::updatemyclassvalue<short int>(t value) { objmyclass.var2 = value; }
more elegant , type-safe.
Comments
Post a Comment