C++ 0x是否支持匿名内部类?

jma*_*erx 3 c++ c++11

假设我有用C++ 98构建的监听器,它们是抽象的,例如必须实现ActionPerformed.在C++中,有一种方法可以类似于Java:

button.addActionListener(new ActionListener() {
public void actionPerfored(ActionEvent e)
{
// do something.
}
});
Run Code Online (Sandbox Code Playgroud)

谢谢

Ger*_*ald 6

不完全是,但你可以用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 )
   {
       ...
   }
));
Run Code Online (Sandbox Code Playgroud)

  • 一个合适的C++接口当然会有任何这样的"addActionListener"采用一个*适当的*函子,一个重载`operator()`,而不是重写虚函数并依赖继承. (4认同)

Ben*_*igt 5

不,你不能那样做.

但是,如果你放弃"类似于Java",只使用一个仿函数,你会发现C++ 11 lambdas非常有用.

  • 你有很多使用Java方法的*C++代码*?试图假装C++是Java不是最理想的,肯定会让你的生活变得悲惨. (7认同)

ken*_*ytm 5

这是C++,而不是Java,因此编写像Java这样的C++不会很好.

无论如何,您可以创建适配器功能.假设

typedef int ActionEvent; // <-- just for testing

class ActionListener
{
public:
    virtual void actionPerformed(const ActionEvent& event) = 0;
};
Run Code Online (Sandbox Code Playgroud)

然后我们可以编写一个包含函数对象的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);
}
Run Code Online (Sandbox Code Playgroud)

然后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;
    }));
}
Run Code Online (Sandbox Code Playgroud)

请注意,这远不是惯用的C++,在这里addActionListener()您应该只使用const std::function<void(const ActionEvent&)>&一个模板参数,甚至模板参数以获得最大效率,并直接提供lambda.