Is there a way in C++ to reflect on the "number of levels of pointer" of a variable, (for example, int* a is 1 level, int** b is 2 levels, and int c is 0 levels)
..Other than using typeid and parsing the string that comes out of that?
The reason I'm asking is I am using pointers to member functions, and I need to know whether to invoke the member function as obj->func() or obj.func(), at compile time really.
If obj is a T**, doing obj.*foo is ill-formed. So you only need to figure out whether it is a pointer or a non-pointer. You can use overloading for this.
template<typename T, typename M> void f(T *obj, M m) { // pointer
(obj->*m)();
}
template<typename T, typename M> void f(T &obj, M m) { // not a pointer
(obj.*m)();
}
This has the drawback that it only works with zero-parameter member function pointers, and it won't return the value (if any) that those functions return. You cannot do the following (which can easily be implemented), because both branches will be type-checked
if(is_pointer(obj)) v = (obj->*m)(arg...); else v = (obj.*m)(args...);
What you can do is to just call a function to dereference your object, if it is a pointer
template<typename T> T &deref(T *t) { return *t; }
template<typename T> T &deref(T &t) { return t; }
Then you can say
v = (deref(obj).*m)(args...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With