【发布时间】:2017-08-25 17:44:23
【问题描述】:
我有类模板作为派生类的基类。这个想法是通过 CRTP 技巧利用“静态多态”。
#include <iostream>
template <typename T>
class BASE
{
public:
void write() {static_cast<T*>(this)->write(); }
};
class DER1 : public BASE<DER1>
{
public:
void write(){
std::cout << "Calling write() inside DER1 " << number << std::endl;}
private:
int number = 11;
};
我尝试了 2 种不同的方法来实例化派生类对象,但我发现这两种方法中的一种是不正确的。但我不明白为什么。
int main(void) {
BASE<DER1> der1_objA ;
der1_objA.write();
DER1 der1_objB ;
der1_objB.write();
return 0;
}
事实上,我得到了输出
Calling write() inside DER1 1880535040 [ random number]
Calling write() inside DER1 11 [correct number ]
谁能解释一下问题出在哪里? 非常感谢您。
【问题讨论】:
-
仅当您实际上是基础子对象时才定义静态转换...
-
在
BASE<DER1>实例中没有DER1实例,但只有一个BASE试图将自己投射到它不是的东西 -
最后是切片。
-
@tobi303 答案在这里!! :-) ...我找不到比你更好的措辞了。
-
@skyjack 我也没有:P