c++ - 调用 std::unique_ptr 指向的底层对象的 operator()
问题描述
我有这个类与 operator() 定义:
class Base{
...
public:
int operator()(int arg)
{
return arg+42;
}
virtual void run(void) = 0;
...
};
一些派生类:
class Derived : public Base
{
...
public:
void run(void)
{
//do something
}
};
然后就是这个数据结构
struct Routine
{
const uint16_t routine_id;
std::unique_ptr<Base> callback;
};
const Routine routines[] = {
{ 0x0001, std::make_unique<Derived>() },
{ 0x0002, std::make_unique<Derived2>() }
// etc
};
通过 p 调用 operator() 的语法是否比这更好:
std::cout << routines[0].callback->operator()(21);
?
解决方案
通过 p 调用 operator() 的语法是否比这更好:
std::cout << routines[0].callback->operator()(21);
?
您可以取消引用指针:
std::cout << (*routines[0].callback)(21);
推荐阅读
- java - Nifi处理中缺少流文件异常导致信息丢失
- javascript - JS 自动滚动代码仅用作 HTML 的一部分,但不能用作 JSFiddle 中的单独脚本
- javascript - 格式化日期数组
- visual-studio-code - 使用带有 remote-ssh 扩展的 Visual Studio Code 时设置环境变量
- android - Profiler 中的内存使用量远低于实际设备
- javascript - 单击带有 reactjs 和 Material UI 的按钮时更改内容
- facebook-graph-api - 在 Instagram 上的当前帐户上按标签搜索内容
- pytorch - 张量的核范数是什么?
- arrays - 在不同的谷歌表格中计算与其案例 ID 匹配的唯一广告系列 ID
- mysql - 如何对两个数据之间的空值进行升序