静态成员函数中的C ++类型的封闭类 [英] C++ type of enclosing class in static member function

查看:149
本文介绍了静态成员函数中的C ++类型的封闭类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这是完全不可能的,但如果。在任何版本的C ++中,是否可以在静态成员函数中以某种方式获取类型的封闭类?

  class Impossible {
public:
static void Fun()
{
typedef不可能的封闭类;

//现在使用EnclosingClass执行某些操作...
}
}

有没有办法得到类型的封闭类(在这种情况下 Impossible ),而没有在函数中写类的名称? / p>

我想这样做的原因是为了避免在函数中重复类名。很容易导致很难找到复制粘贴错误,如果发生这样的事情:

  class SomeOther {// another类,具有相同的界面不可能
public:
static void Fun()
{
typedef不可能EnclosingClass;
//无法复制粘贴,忘记将不可能更改为SomeOther

//现在使用EnclosingClass执行某项操作...
}
}

有没有好的方法来防止这种事情发生?我可以想像在封闭类中声明为私有的东西,但这将迫使我写多余的代码(因为我当前的设计不包含任何固有的私有成员,都是公共的)。

解决方案

问题是C ++缺少一个 self 关键字。



我通常写:

  struct Foo 
{
typedef Foo self;

static void bar()
{
self * ptr = nullptr;
}
};

我知道你还需要确保 typedef 是正确的,但至少这样你可以在类型定义的顶部,你会注意到它。



但是, href =http://stackoverflow.com/q/21143835/560648>您可以将此完全自主化。


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 ...
    }
}

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).

解决方案

The problem is that C++ is lacking a self keyword.

I typically write:

struct Foo
{
   typedef Foo self;

   static void bar()
   {
      self* ptr = nullptr;
   }
};

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.

With hackery, though, you can make this entirely autonomous.

这篇关于静态成员函数中的C ++类型的封闭类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆