CRTP / 宏 / 避免强制转换派生类的指针
CRTP / Macros / Avoid casting pointer of derived class
最近我一直在做一些项目,问题是我们遇到了需要能够做这样的事情的情况。
#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()
返回一个指向B
的B*
。
同样,b1
本身就是指向B
的B*
。
b2->typedThis()
返回一个指向B
的A*
。
同样,b2
本身就是一个指向B
的A*
。
所以b1->typedThis()
和b1
一样,b2->typedThis()
和b2
一样,例子的最后两行等效于下面:
std::cout << b1->x << "n";
std::cout << b2->x << "n";
另请注意,C 样式强制转换会丢弃对象的const
限定符。
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 如何使用基类指针引用派生类成员
- 将派生指针分配给C 中的其他派生类型
- 如何通过派生指针调用基类中的模板成员函数
- 如何将带有恒定指针作为参数的模板的派生指针使用
- 无法返回包含派生指针的向量
- 如何创建派生指针类变量
- C++强制转换为派生指针或设计错误
- 无法从派生指针访问公共基成员
- C++发送派生指针作为参数
- 将专用基指针强制转换为专用于其他模板参数的派生指针("adding on"专用化)
- 在派生指针上显式调用基类析构函数时编译错误
- 安全派生指针值的示例
- 安全派生指针的整数表示形式
- c++多态克隆:如何从基指针获得派生指针
- 如果我将派生指针转换为基指针,这两个指针是否保证具有相同的值?
- 以任何方式将基指针强制转换为派生指针是否危险
- 将派生指针隐式强制转换为其相应基类的引用
- 当派生指针仅添加方法时,将基指针强制转换为派生指针的有效性
- c++转换指针到派生指针到基指针的例子