An overloaded function template is a savior:
template<typename T> void invoke(T * obj) //when object is pointer { obj->Process(); } template<typename T> void invoke(T & obj) //when object is non-pointer { obj.Process(); }
then use it like:
auto value = it->second; invoke(value);
But this is not good enough, since you can do something else with value in the rest of the function you wrote. Therefore, if you follow the approach described above, code duplication will occur, since both invoke() will have almost similar code.
So, here is one improvement: instead of using invoke() , turn the pointer into a link so that you can use it evenly in your function.
template<typename T> T& ensure_ref(T * obj) //when object is pointer { return *obj; //return the dereferenced object } template<typename T> T& ensure_ref(T & obj) //when object is non-pointer { return obj; //simply return it }
And use it like:
auto & value = ensure_ref(it->second); //call ensure_ref to ensure reference! value.Process(); //value is gauranteed to be NOT pointer! //you might want to do this also! value.xyz = abc;
Hope this helps!
Nawaz source share