2

When you're in a C++ non-static method, you can use the this variable to refer to the current instance; and through the instance you also have the type. In static methods, I would expect to have something like a this_class type available to me, which is the type of the class in which I'm implementing the method. Even if it's not inherited (i.e. for class B : public A, method A::foo() will have this_class being A even when accessed through B) - it would still be useful, for example when you're implementing a static method in a class with many template arguments, and you want to call some out-of-class function templated on your class's type.

Illustration of use:

template <typename T> void foo() { std::cout << typeid(T).name(); }

template <typename S, typename T, typename U, typename AndLots, typename More>
class A {
    /* ... */
    static void say_my_name( foo<this_class>(); }
}

So, was this possibility ever considered? Are there reasons it would complicate things for the developer or the compiler?

einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

1

How come there's no 'this_class' - the static equivalent of 'this'?

You don't need it, because it's trivial.

You can either write

template <typename S, typename T, typename U, typename AndLots, typename More>
class A {
    public:
    /* ... */
    static void say_my_name() { foo<A>(); }
                                // ^^^
};

Demo

or

template <typename S, typename T, typename U, typename AndLots, typename More>
class A {
    public:
    /* ... */
    typedef A<S,T,U,AndLots,More> this_type;

    static void say_my_name() { foo<this_type>(); }
};

Demo

if you prefer.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • The "this type" is what I want to have without specifying it explicitly. So, your answer is that it's not useful enough to have in the language? – einpoklum Apr 23 '16 at 10:24
  • 1
    _"So, your answer is that it's not useful enough to have in the language?"_ Yes, that's what I meant. For most cases you should get away with my 1st sample. – πάντα ῥεῖ Apr 23 '16 at 10:26
  • @einpoklum See also [this](http://coliru.stacked-crooked.com/a/1187732870f863ef) or [this](http://coliru.stacked-crooked.com/a/0a9b07fc26bd5d91). – πάντα ῥεῖ Apr 23 '16 at 13:03