繁体   English   中英

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

[英]Does C++0x support Anonymous Inner Classes?

假设我有用C ++ 98构建的监听器,它们是抽象的,例如必须实现ActionPerformed。 在C ++中,有一种方法可以类似于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 lambdas非常有用。

这是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。

我想我们可以使用lambdas在C ++中做到这一点

button.addActionListener([]()->ActionListener*{ struct A: ActionListener {
void actionPerfored(ActionEvent e)
{
// do something.
}
}; return new A;}());

将它包装在宏中应该很容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM