0

为什么this不允许在静态成员函数的未评估上下文中使用?

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

此代码给出错误:

错误:“this”对于静态成员函数不可用

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

decltype(this)需要简洁(有时它更短,然后VeryVeryLongClassName *),另一个优点是意图更清楚。

this关于在静态成员函数中未评估的上下文中使用的标准是什么?

4

1 回答 1

5

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;
};
于 2017-09-07T05:35:35.533 回答