Pregunta

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

¿Fue útil?

Solución

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.

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top