C++ type of enclosing class in static member function

南楼画角 提交于 2019-11-27 09:13:38
Lightness Races in Orbit

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++ does not have any feature to get the name of the current class, namespace, etc. In C++11 you can get type of the variable, but you need the variable in the first place. In this case you do not have anything to start with.

I like the idea of trying to introduce some general name that you can refer to in unrelated classes; for maintainability.

My first approach would be a simple one: Provide a typedef in the enclosing class. Give the typedef the same name in every unrelated class.

class Impossible {
public:
    typedef Impossible Enclosing;
    static void Fun()
    {   
        Enclosing* theObject = 0;
    }   
};

Doing this will also have the effect -- and I would call it a benefit -- of failing to compile in new unrelated classes where you haven't provided the typedef.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!