Search code examples
c++c++14c++17static-membersstatic-functions

this in unevaluated context in static member functions


Why this is not allowed in unevaluated context in static member functions?

struct A
{
    void f() {}
    static void callback(void * self) // passed to C function
    {
        static_cast< decltype(this) >(self)->f();
    }
};

This code gives an error:

error: 'this' is unavailable for static member functions

static_cast< decltype(this) >(self)->f();
                      ^~~~

decltype(this) there is needed for brevity (sometimes it is much more shorter, then VeryVeryLongClassName *), another advantage is the fact that intention is more clear.

What Standard says about using this in unevaluated contexts in static member functions?


Solution

  • I don't see how it matters that this appears within an unevaluated context, you've referred to something that doesn't exist in a static member function, so how is the compiler supposed to deduce the type of this within this context?

    As a corollary, the type of this in a non-static member function is dependent on the cv-qualifier of said member function, decltype(this) would yield T const* if the member function were const, and T * if it weren't. Thus, the type is dependent on the context of the expression. In your example, the context has no this pointer.

    To alleviate the pain of having to name the class you could add an alias for it.

    class VeryVeryLongClassName
    {
        using self = VeryVeryLongClassName;
    };