在 c++ 中使用闭包更改行为
Changing behaviour using a closure in c++
>我有一个基类和一个闭包,基类总是由特定的类扩展,但它没有确定基类具体包含什么。
现在我想在更改特定类的行为的同时覆盖基类的行为。
以下是我想要实现的目标的简单示例:
class base
{
public:
inline void print()
{
std::cout << "test!" << std::endl;
}
};
template <class T>
class closure
{
public:
inline closure()
{
if (!std::is_convertible<T*, base*>::value) {
throw "error!";
}
this->baseInstance = new T();
}
/*
* In this class the behavior of test should be extended/overridden.
* in this case base::print
*/
~closure()
{
delete this->baseInstance;
}
inline T * operator-> ()
{
return this->baseInstance;
}
private:
T * baseInstance;
};
class test : public base
{
public:
inline void otherStuff()
{
/* ... **/
}
/* .. */
};
在这种情况下,我想覆盖base::print()
,但在通过闭包调用test::otherStuff()
时保持它的全部功能。
好的,我自己找到了解决方案。
最后很容易,因为我知道我想改变什么功能,我将基类的整个函数编写为std::function<void()>
然后我与闭包交朋友,以便它能够覆盖它。
base::print()
的方法调用已更改为std::function<void()>
的调用,现在它运行良好。
相关文章:
- 如何将C++闭包与变量参数同时重用——类似于JavaScript
- C++中的 JavaScript 样式闭包
- 如何使用类模拟 C++11 中的 lambda 函数和闭包?
- 使用带有闭包的 lambda 的回调
- C++中的 Lambda <-> 闭包等价性
- 为什么 std::remove_if 会创建如此多的闭包?
- Lambda闭包左值可以作为右值参考参数传递
- 如何声明接受字符串、返回void的闭包的类型
- 添加了闭包的 Perl newXS()
- 具有意外结果的 C++ 闭包
- 关于函数模板中定义的 lambda 闭包类型可以说些什么?
- 基类如何调用派生类在 c++ 中传递的闭包?
- 通过引用将自定义结构的向量传递给 boost::compute 闭包或函数
- 创建特征以检测C++中的闭包类型
- 在 c++ 中使用函数装饰器(使用闭包)时出现意外的分段错误
- Lambda 表达式闭包函数不起作用
- Lambda 闭包类型构造函数
- 在闭包中,如何通过存储在内存中的指针或引用类型捕获可变性或用现代函数式语言进行处理?
- boost::compute,将指针传递给闭包
- 没有声明和初始化的类似闭包的函数(即没有'auto f = make_closure();')