C++模板是否能够从父类"forward any class function"?

Is a C++ template able to "forward any class function" from parent class?

本文关键字:forward any class function 父类 是否 C++      更新时间:2023-10-16
class Foo {
public:
  void methodA();
};
class ManagedFoo {
Foo fooInst;
public:
  void methodA() { doSomething(); fooInst.methodA();}
};

现在我想将 ManagedFoo 作为一个模板,不仅管理 Foo 的任何类,并且在调用任何 Foo 的函数之前,首先调用 doSomething。

template<typename _TyManaged>
class Manager {
  _TyManaged _managedInst;
  void doSomething();
public:
  /*Forward every function called by _managedInst*/
  /*How to write this?*/
};

我想让它相同,让它在这两个类之间可替换,就像这样:

Foo* foo = new Foo();
foo->methodA();
Manager<Foo> managedFoo = new Manager<Foo>();
managedFoo->methodA(); //Hope it call Manager::doSomething() first then call _managedInst.methodA();

C++11模板可以做这样的事情吗? 如果答案是肯定的,如何做?

基于运算符>重载的解决方案:

#include <iostream>
#include <memory>
class A {
public:
    void foo() { std::cout << "foon"; }
    void bar() { std::cout << "barn"; }
};
template <typename T>
class ManagedBase {
    std::shared_ptr<T> _inst;
public:
    ManagedBase(const std::shared_ptr<T> inst) : _inst(inst) { }
    virtual ~ManagedBase() { }
    std::shared_ptr<T> operator->() {
        before();
        return this->_inst;
    }
    virtual void before() =0;
};

template <typename T>
class ManagedPrint : public ManagedBase<T> {
public:
    ManagedPrint(const std::shared_ptr<T> inst) : ManagedBase(inst) { }
    virtual void before() {
        std::cout << "Said: ";
    }
};

int main() {
    auto ma = ManagedPrint<A>(std::make_shared<A>());
    ma->bar();      // Said: foo
    ma->bar();      // Said: bar
}

像这样的东西?

template<typename _TyManaged>
class Manager {
  _TyManaged _managedInst;
  void doSomething();
public:
  _TyManaged* operator->() {
    doSomething();
    return &_managedInst;
  }
};

这可以解决您的问题。但我仍然不确定你想用你的经理类做什么。

class Foo {
  public:
    void methodA();
};
template<typename T>
class ManagedFoo : public T {
  public:
    // some further extensions
};

当然,通过这种方式,您将管理器对 Foo 类的语义从:
它有一个

这是一个
所以我不确定在你的情况下这是否属实。