C++模板是否能够从父类"forward any class function"?
Is a C++ template able to "forward any class function" from parent class?
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 类的语义从:
它有一个
自
这是一个
所以我不确定在你的情况下这是否属实。
相关文章:
- 哪些类型可以转换为std::any
- 完美前进使用 std::forward vs RefRefCast
- 引用 std::any 或 not_yet_in_std::whatever 的惯用方式是什么?
- 你如何理解"std: :forward is just syntactic sugar"?这是真的吗?
- "std::forward"和"std::move"真的不生成代码吗?
- 在C++中使用 std::forward 的多个参数
- std::is_reference from std::any
- 如何使用 std::forward 精确地评估参数包的扩展?
- 是否可以从 std::any 创建 std::any 与 std::reference_wrapper?
- "reserved for any use"的含义是什么?
- boost::any 如何检查空值/未定义的值
- 使用 std::map 存储在 std::any 中,然后通过 std::any_cast 访问
- 可以有效地转换 std::any 与 std::any_cast
- 避免使用 std::any 编写相同的重复类型检查代码
- 广义 std::function (std::any 表示可调用对象)
- 普通的右值引用和 std::forward 返回的引用有什么区别?
- 如何在 c++17 中获取存储在 "any" 中的数据大小?
- 从 Any 包中提取和匹配 protobuf 消息类型名的首选方法
- 怎么可能写 f( *this, std::forward<Args>(args)... ) 而 f 只用 F f 声明;
- C++模板是否能够从父类"forward any class function"?