CRTP / 宏 / 避免强制转换派生类的指针

CRTP / Macros / Avoid casting pointer of derived class

本文关键字:派生 指针 转换 CRTP      更新时间:2023-10-16

最近我一直在做一些项目,问题是我们遇到了需要能够做这样的事情的情况。

#define TYPED(Type) 
    virtual Type *typedThis() const { return (Type*) this; }
class A {
public: 
TYPED(A)
virtual void describe() { std::cout << "I am type An"; }
static int x;
};
int A::x = 1;
class B : public A {
public: 
TYPED(B) 
virtual void describe() { std::cout << "I am type Bn"; }
static int x;
};
int B::x = 2;
int
main(int argc, char** argv)
{
    B* b = new B();
    A* b2 = b;
    b->describe();
    b2->describe();
    std::cout << b->typedThis()->x << std::endl;
    std::cout << b2->typedThis()->x << std::endl; // AQUI DEBERIA DAR 2 !! :c
}

这当然只是一个玩具的例子。我们想要做的的基本思想是定义一个函数 typedThis((,它将指针转换为正确的类型,然后访问正确的变量 x,并打印出 2 而不是 1。

但是,输出如下:

I am type B
I am type B
2
1 //Here should also be 2

我发现真正有趣的是,虚拟方法 describe(( 似乎正在按照我们想要的方式工作。因此,我可以推断 typedThis(( 方法也按照我们想要的方式工作。但如果是这样,为什么C++将此指针视为 A* 而不是 B*。如果C++看到这个指针像 B* 一样,那么它将使用正确的变量 x。 有人可以向我解释一下吗?

我尝试使用 CRTP,但是

我觉得这不会让事情变得更容易,因为在项目中我们将使用很多(很多(不同的类,这些类不断在它们之间派生,我看到了一些关于如何在多重继承时使用 CRTP 的文章,但是它们真的很混乱,很难与我们目前所拥有的东西集成。

我从示例中消除了所有干扰:

class A {
public: 
    virtual A *typedThis() const { return (A*) this; }
    static int x = 1;
};
class B : public A {
public: 
    virtual B *typedThis() const { return (B*) this; }
    static int x = 2;
};
int main()
{
    B* b1 = new B;
    A* b2 = b1;
    std::cout << b1->typedThis()->x << "n";
    std::cout << b2->typedThis()->x << "n";
}

typedThis什么都不做。

b1->typedThis()返回一个指向BB*

同样,b1本身就是指向BB*

b2->typedThis()返回一个指向BA*

同样,b2本身就是一个指向BA*

所以b1->typedThis()b1一样,b2->typedThis()b2一样,例子的最后两行等效于下面:

    std::cout << b1->x << "n";
    std::cout << b2->x << "n";

另请注意,C 样式强制转换会丢弃对象的const限定符。