c++ 0x支持匿名内部类吗?
Does C++0x support Anonymous Inner Classes?
假设我有c++ 98内置的侦听器,它们是抽象的,必须例如实现ActionPerformed。在c++ 0x中是否有类似于Java的方法:
button.addActionListener(new ActionListener() {
public void actionPerfored(ActionEvent e)
{
// do something.
}
});
谢谢
不完全是这样,但是你可以用Lambdas做一些类似的事情。
即:
class ActionListener
{
public:
typedef std::function<void(ActionEvent&)> ActionCallback;
public:
ActionListener( ActionCallback cb )
:_callback(cb)
{}
void fire(ActionEvent& e )
{
_callback(e);
}
private:
ActionCallback _callback;
};
..
button.addActionListener( new ActionListener(
[]( ActionEvent& e )
{
...
}
));
不,你不能这么做。
如果你放弃"类似于Java",而只使用函子,你会发现c++ 11 lambda非常有用。
这是c++,不是Java,所以像Java那样写c++是不行的。
无论如何,您可以创建一个适配器函数。假设typedef int ActionEvent; // <-- just for testing
class ActionListener
{
public:
virtual void actionPerformed(const ActionEvent& event) = 0;
};
然后我们可以写一个ActionListener的模板化子类来包装一个函数对象:
#include <memory>
template <typename F>
class ActionListenerFunctor final : public ActionListener
{
public:
template <typename T>
ActionListenerFunctor(T&& function)
: _function(std::forward<T>(function)) {}
virtual void actionPerformed(const ActionEvent& event)
{
_function(event);
}
private:
F _function;
};
template <typename F>
std::unique_ptr<ActionListenerFunctor<F>> make_action_listener(F&& function)
{
auto ptr = new ActionListenerFunctor<F>(std::forward<F>(function));
return std::unique_ptr<ActionListenerFunctor<F>>(ptr);
}
,然后使用make_action_listener
包装lambda,例如(http://ideone.com/SQaLz)。
#include <iostream>
void addActionListener(std::shared_ptr<ActionListener> listener)
{
ActionEvent e = 12;
listener->actionPerformed(e);
}
int main()
{
addActionListener(make_action_listener([](const ActionEvent& event)
{
std::cout << event << std::endl;
}));
}
请注意,这与c++的习惯用法相差甚远,在addActionListener()
中,您应该简单地使用const std::function<void(const ActionEvent&)>&
,甚至是模板参数以获得最大效率,并直接提供lambda。
我认为我们可以在c++中使用lambdas
button.addActionListener([]()->ActionListener*{ struct A: ActionListener {
void actionPerfored(ActionEvent e)
{
// do something.
}
}; return new A;}());
相关文章:
- 在设计 SDK 时,我是否应该在 C++ 头文件中完全隐藏内部类?
- 如何声明由多个线程调用的 C++ DLL 的内部类,而无需导出类
- 从内部类继承
- 如何将枚举类转发声明为模板化类的内部类?
- 从内部类中的方法从包含类调用方法
- 从模板化父类中的派生内部类访问受保护的成员变量
- C++模板类的内部类访问
- 使用类模板的内部类模板专用化模板
- 如何使用包含内部类的类实例有效地从内部类访问成员?
- C++ 如何在外部类中声明的内部类中使用变量
- 在C++中将内部类实现为具有名称空间的独立类有什么好处
- 参数化类的别名(或类型定义)内部类
- 从内部类的析构函数调用虚拟函数
- 如何在没有setter的情况下设置类内部类的成员变量?
- 具有相同名称的方法和内部类(错误:.. 与前面的声明冲突)
- 内部类私有成员访问和封闭的友好性
- 在C++中从内部类对象获取外部类对象
- 在它所属的模板类中使用内部类
- C++命名空间、内部类和运算符解析
- c++ 0x支持匿名内部类吗?