Is there any way to assign a pointer-to-class-member so that it points to the class itself?
This would effectively mean that the result of applying the member pointer to an instance of the class would be a reference to that very same instance.
eg:
struct SFoo {};
constexpr SFoo SFoo::* MP_foo = &SFoo:: MYSELF;
// Is there some syntax I can use here? --^
The reason I want this is I have a sorting algorithm that works on a container of elements of an arbitrary template type. The sorting key is obtained from each element using a supplied pointer-to-member.
However, I now wish to sort a container where the element is also the key. Thus, I need to make the member-pointer point to itself (as if the class were its own member).
There are a number of easy (and zero cost) hacks I can use (and I'm using one now), but I want to know if there's some syntactical trick I can use to get it done the right way - to avoid extra inelegant code.
Unfortunately the question is not very clear (but -1 is not mine). My impression is that you are confusing the type of the object that is to be sorted (in your case this is SFoo), and the type of the sorting key. In a typical situation they are different. Ex: Users to be sorted (object) and the sorting key is the first and the last name (a pair of strings). You are not stating the type of the sorting key directly.
Syntactically SFoo SFoo::* MP_foo
is a pointer to the instance field whose type is SFoo. C++ does not allow that because otherwise this will cause infinite recursion. This field will have SFoo filed and that inner field will need to have this field again.
Second, you are trying to initialize pointer to a data with the pointer to a function. Constructor SFoo::SFoo
is a function. And as it is mentioned in comments, the addresses of ctors are not allowed.
One more attempt: Applying the member pointer to an instance of the class would be a reference to that very same instance.
Pointer to member points to a member. The object is not its member. Good or bad this is how C++ is defined.
You might try to define a wrapper class, something like:
struct SFoo2
{
SFoo m_data_field;
};
Note that from the point of view of memory layout they will be identical. SFoo2
can have pointer to member of type SFoo
. I am not sure if this will work in your context, but you may give it a try.