Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store or reflect on the "reference level" of a variable

Tags:

c++

variables

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.

like image 212
bobobobo Avatar asked Dec 09 '25 10:12

bobobobo


1 Answers

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...);
like image 131
Johannes Schaub - litb Avatar answered Dec 12 '25 00:12

Johannes Schaub - litb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!