首页 > 解决方案 > 调用 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);

?

标签: c++

解决方案


通过 p 调用 operator() 的语法是否比这更好:

std::cout << routines[0].callback->operator()(21); 

?

您可以取消引用指针:

std::cout << (*routines[0].callback)(21);

推荐阅读