简体   繁体   English

在静态成员函数中未评估的上下文中

[英]this in unevaluated context in static member functions

Why this is not allowed 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();
    }
};

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. decltype(this)为了简洁起见是需要的(有时它要短得多,然后是VeryVeryLongClassName * ),另一个优点是意图更清晰。

What Standard says about using this in unevaluated contexts in static member functions? 对于在静态成员函数的未评估上下文中使用this标准,标准说了什么?

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? 我不明白它是如何重要的是this会出现一个未计算的环境中,你提到的东西, 不存在一个静态成员函数,所以编译器应该如何演绎的类型this此范围内?

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. 作为推论,非静态成员函数this类型取决于所述成员函数的cv-qualifier,如果成员函数为const ,则decltype(this)将产生T const*如果不是,则为T * t。 Thus, the type is dependent on the context of the expression. 因此,类型取决于表达式的上下文。 In your example, the context has no this pointer. 在您的示例中,上下文没有this指针。

To alleviate the pain of having to name the class you could add an alias for it. 为了减轻必须为类命名的麻烦,您可以为其添加别名。

class VeryVeryLongClassName
{
    using self = VeryVeryLongClassName;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM