c++ - 如何在 CRTP 实现中传递基类指针
问题描述
我正在将具有纯虚拟方法的普通继承的代码转换为 CRTP,以避免虚拟方法的开销(请参见此处)。
转换工作得非常好,直到我删除了 CRTP 实现中调用方法的注释(它给出compilation error: use of undeclared identifier 'T'
) 如何在 CRTP 中实现相同的调用方法,这在普通继承中没有问题?换句话说,是否可以像普通继承一样将指针传递给基类?
当然,我可以通过在类模板中移动调用方法来解决问题,但是对于我的用例,它不属于那里(我这里没有给出我的实际代码,这很长)。有任何想法吗?
转换前的代码如下:
#include <iostream>
class Base
{
public:
void interface() {
implementation();
}
virtual void implementation() = 0;
};
class Derived1 : public Base
{
public:
void implementation() {
std::cout << "Hello world 1" << std::endl;
}
};
class Derived2 : public Base
{
public:
void implementation() {
std::cout << "Hello world 2" << std::endl;
}
};
void call(Base *b) {
b->interface();
// ... do other things ...
}
int main() {
Derived1 d1;
Derived2 d2;
call(&d1);
call(&d2);
}
转换后的代码 (CRTP) 如下所示:
#include <iostream>
template <class T>
class Base
{
public:
void interface() {
static_cast<T*>(this)->implementation();
}
};
class Derived1 : public Base<Derived1>
{
public:
void implementation() {
std::cout << "Hello world 1" << std::endl;
}
};
class Derived2 : public Base<Derived2>
{
public:
void implementation() {
std::cout << "Hello world 2" << std::endl;
}
};
//void call(Base<T> *b) {
// b->interface();
// // ... do other things ...
//}
int main() {
Derived1 d1;
Derived2 d2;
//call(&d1);
//call(&d2);
d1.interface();
d2.interface();
}
解决方案
你错过了一些语法。正确声明:
template<class T> // <--- this was missing
void call(Base<T> *b) {
b->interface();
}
推荐阅读
- node.js - 无法使用阿里云函数计算 Serverless 插件创建新函数
- python - 具有分层类别的样本
- mule - 数字格式在 Mulesoft 数据视图中不起作用
- html - 需要修复引导垂直选项卡的“上一个”和“下一个按钮”单击选项卡
- c# - 将 Linux 日期时间转换为 Windows 本地日期时间格式
- python - Pandas datetools 模块错误
- amazon-web-services - 使用 Spring Boot 代码运行 docker 容器
- c# - 从组合的 csv 文件创建数据表时出错
- oauth-2.0 - Google Home 授权码和使用 Google 帐户的身份验证
- keras - Keras:在某一层后停止渐变