this 在静态成员函数的未计算上下文中

this in unevaluated context in static member functions

为什么在静态成员函数的未计算上下文中不允许 this

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

这段代码报错:

error: 'this' is unavailable for static member functions

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

decltype(this)需要简洁(有时更短,然后VeryVeryLongClassName *),另一个好处是意图更明确。

关于在静态成员函数的未计算上下文中使用 this,标准有何规定?

我不明白 this 出现在未计算的上下文中有什么关系,你在静态成员函数中引用了 doesn't exist 的东西,那么编译器应该如何在此上下文中推断 this 的类型?

作为推论,非静态成员函数中的 type of this 取决于所述成员函数的 cv 限定符,如果成员函数 decltype(this) 将产生 T const*const,如果不是 T *。因此,类型取决于表达式的上下文。在您的示例中,上下文没有 this 指针。

为了减轻必须命名 class 的痛苦,您可以为其添加别名。

class VeryVeryLongClassName
{
    using self = VeryVeryLongClassName;
};

标准的当前草案有some conflicting information

If a declaration declares a member function or member function template of a class X, the expression this is a prvalue of type "pointer to cv-qualifier-seq X" wherever X is the current class between the optional cv-qualifier-seq and the end of the function-definition, member-declarator, or declarator. It shall not appear within the declaration of either a static member function or an explicit object member function of the current class (although its type and value category are defined within such member functions as they are within an implicit object member function).

首先它禁止在静态成员函数中使用表达式this,然后说this的类型和值类别是在静态成员函数中定义的(并且它在一个解决 cv 资格问题的方法)。如果没有办法引用所述 this 来获取其类型,这似乎没用。

可能的解决方案是将规则从“不得出现”更改为“不得评估”,这将立即允许它出现在未评估的上下文中,例如 decltypesizeof.