问题描述
我认为这是完全不可能的,但是如果.是否可以在任何版本的 C++ 中以某种方式在静态成员函数中获取封闭类的类型?
I assume this is outright impossible, but what if. Is it possible to somehow get type of enclosing class in a static member function, in any version of C++?
class Impossible {
public:
static void Fun()
{
typedef Impossible EnclosingClass;
// now do something with EnclosingClass ...
}
}
有没有办法在不将类名写入函数的情况下获取封闭类的类型(在本例中为Impossible
)?
Is there a way to get the type of the enclosing class (Impossible
in this case) without writing the name of the class in the function?
我想这样做的原因是为了避免在函数中重复类名.如果发生这样的事情,很容易导致难以找到的复制粘贴错误:
The reason why I'd like to do that is to avoid repeating the class name in the function. It could easily lead to a hard to find copy-paste bug, if something like this happened:
class SomeOther { // another class, with the same interface as Impossible
public:
static void Fun()
{
typedef Impossible EnclosingClass;
// whoops, copy-pasted, forgot to change "Impossible" to "SomeOther"
// now do something with EnclosingClass ...
}
}
有什么好的方法可以防止这种事情发生吗?我可以想象触及在封闭类中声明为私有的东西,但这将迫使我编写额外的代码(因为我当前的设计不包含任何固有的私有成员,所有成员都是公开的).
Is there a good way to prevent this kind of thing happening? I could imagine touching something that was declared private in the enclosing class, but that would be forcing me to write extra code (as my current design doesn't contain any inherent private members, all is public).
推荐答案
问题在于 C++ 缺少 self
关键字.
The problem is that C++ is lacking a self
keyword.
我通常写:
struct Foo
{
typedef Foo self;
static void bar()
{
self* ptr = nullptr;
}
};
我意识到你仍然需要确保 typedef
是正确的,但至少这样你可以将它放在类型定义的顶部,你会注意到它.
I realise you still have to make sure the typedef
is correct, but at least this way you can have it at the top of the type definition where you'll notice it.
不过,有了hackery,您可以完全自主.
With hackery, though, you can make this entirely autonomous.
这篇关于静态成员函数中封闭类的C++类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!