the*_*ine 16 c++ static-methods types
我认为这是完全不可能的,但如果.在任何版本的C++中,是否有可能以某种方式在静态成员函数中获取封闭类的类型?
class Impossible {
public:
static void Fun()
{
typedef Impossible EnclosingClass;
// now do something with EnclosingClass ...
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法获得封闭类的类型(Impossible
在这种情况下)而不在函数中写入类的名称?
我之所以这样做,是为了避免在函数中重复类名.如果发生这样的事情,很容易导致难以找到的复制粘贴错误:
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 ...
}
}
Run Code Online (Sandbox Code Playgroud)
有没有一种好方法可以防止这种事情发生?我可以想象触摸在封闭类中声明为私有的东西,但这会强迫我编写额外的代码(因为我当前的设计不包含任何固有的私有成员,都是公共的).
问题是C++缺少self
关键字.
我通常写道:
struct Foo
{
typedef Foo self;
static void bar()
{
self* ptr = nullptr;
}
};
Run Code Online (Sandbox Code Playgroud)
我意识到你仍然必须确保它typedef
是正确的,但至少这样你可以将它放在类型定义的顶部,你会注意到它.
但是,有了hackery,你可以完全自主.