Class方法调用变量方法

Class method to call variable method

我现在的情况是这样的结构:

class Foo {
    public:
        void call() {
            b.call();
        }
    private:
        Bar b;
};

class Bar {
    public:
        void call() {
            std::cout << "Hello there" << std::endl;
        }
};

int main() {
    Foo f;

    f.call(); // This calls directly the b.call() function
}

有没有语法可以直接让Foo.call函数直接调用class里面的函数存储为变量?

基本上,有没有一种语法可以做类似的事情:

class Foo {
    public:
        void call() -> b.call
    private:
        Bar b;
};

你说的是语言级别的 delegate 构造。有些语言内置了对此的支持,但 C++ 没有。你必须像以前那样 "hard way" 去做。

如果这是一个非常普遍的事情,您可以定义一个宏,但使用丑陋的代码通常比令人困惑或误导的代码要好。

像这样尝试帮助编译器一般是没有必要的。编译器非常擅长优化这类事情。您不需要告诉编译器 Foo::call 实际上只是一个 Bar::call。编译器会弄清楚的。考虑一个稍微调整过的例子:

extern void DisplayMessage(char const*);

class Bar {
public:
  void call() {
    DisplayMessage("Hello there");
  }
};

class Foo {
public:
  void call() {
    b.call();
  }
private:
  Bar b;
};

int main() {
  Foo f;

  f.call(); // This calls directly the b.call() function
}

当我使用 Clang 7.0 和 -O3 编译它时,我得到以下信息:

main:                                   # @main
    push    rax
    mov     edi, offset .L.str
    call    DisplayMessage(char const*)
    xor     eax, eax
    pop     rcx
    ret

请注意,编译器已完全删除对象,只留下对 DisplayMessage 函数的直接调用。

您的代码可能更短:

class Bar {
public:
    void call() const {
        std::cout << "Hello there" << std::endl;
    }
};

class Foo : private Bar // private is superfluous here, as we use class instead of struct
{
public:
    using Bar::call;
};

不过人工转发的排版方式看起来更自然