2017-09-07 47 views
0

为什么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

+0

([在静态成员函数封闭类的C++型]的可能的复制https://stackoverflow.com/questions/21143275/c-type-of-enclosing-class-in-static-member-function ) –

回答

6

我不明白它是如何重要,一个未计算的背景下出现this,你提到的东西,doesn't exist在一个静态成员函数,因此,如何编译器应该推断的this此范围内的类型?

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

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

class VeryVeryLongClassName 
{ 
    using self = VeryVeryLongClassName; 
};