Reputation: 73
In Python, there's a self
variable that refers to the instance itself, and a cls
object (for class methods) that refer to the class. In the same manner, there's a 'this' pointer pointing to the calling object; but I'm not aware of any pointer to the class itself, I'm familiar with using something like this...
ClassName::memberFunction(this)
But it's not what I want.
I guess it's pretty obvious that there's no such thing, given how constructors still make use of their class's name, but why not make it a feature in C++?
Upvotes: 1
Views: 149
Reputation: 217810
C++ doesn't have this kind of keyword allowing something like:
class C
{
Self(const Self&) = default; // Not valid
~Self() = default; // Not valid
};
You could simulate it with MACRO:
class C
{
#define Self C
Self(const Self&) = default;
~Self() = default;
#undef Self
};
but why not make it a feature in C++?
You can still try to create a proposal for that.
Whereas using it in class definition seems fine, using it outside seems problematic:
C::C(const C&) {} // Regular way
Self::Self(const Self&) {} // Which class ?
C::Self(const Self&) {} // Mix C and Self
Upvotes: 1
Reputation: 275730
Inside a method of the class, the tokens
std::decay_t<decltype(*this)>
will evaluate to the type name of this
.
Outside of a method there is no similar technique.
It isn't in the language, because nobody has gotten such a feature through the committee. It would take work.
A number of compilers have extensions that resolve to the "parent class". I'm unaware of a compiler that has the extension for "type of enclosing class".
Upvotes: 1
Reputation: 238401
but I'm not aware of any pointer to the class itself
A class is not an object, so there can not be a pointer to a class.
Within other member functions (i.e. the only places you may have access to this
in the first place), you can refer to static member functions simply by their name:
struct S {
static void foo(){}
void bar() {
foo();
}
};
Upvotes: 1