Can I create an anonymous class "on the fly" (interface implementation) in C ++

In C ++, can I create an implementation of the interface on the fly (which ideally binds local scope variables). Not sure how to explain this better, so I will put what I would like the code to look like (approximately):

// Given the following:

class Visitor
{
    virtual void visit(const Data& data) = 0;
}

class DataStore
{
    void visitData(Visitor& visitor) { /** Invokes visitor with each item of data. */ }
}

// Imagine one would write something like:

void inSomeFunction(DataStore& store)
{
    std::string myName = "bob";

    class MyVisitor: public Visitor
    {
    public:
        MyVisitor(const std::string& p): person(p);
        virtual void visit(const Data& data) override
        {
            std::cout << person << " is visiting " << data << std::endl;
        }
    private:
        std::string person;
    }

    MyVisitor myVisitor(myName);
    store.visitData(myVisitor);
}

// Instead of the above, I want to write instead something like:

void inSomeFunction(DataStore& store)
{
    std::string myName = "bob";

    store.visitData(
        class: public MyVisitor
        {
            virtual void visit(const Data& data) override
            {
                std::cout << myName << " is visiting " << data << std::endl;
            }
        }
    );
}

I understand that I am asking 2 questions here - can you create an anonymous class like this, and can you bind variables from the local scope (for example, I referenced myName). But I need both to be useful.

If the above cannot be done, then what is closest possible to use for using C ++ 11 lambdas or similar in terms of brevity / lack of template.

+4
2

, , Kerrek.

:

class DataStore
{
    void visitData(Visitor& visitor) { 
        // bunch of calls to visitor.visit(...) ... 
    }
}

    template <class Visitor>
    void visitData(Visitor visitor) { 
        // bunch of calls to visitor(...) ... 
    }

:

std::string myName = "bob";
store.visit([myName](const Data& data) {
    std::cout << myName << " is visiting " << data << std::endl;
});

, . DataStore , .

+9

:

#include <functional>
#include <utility>

class AdHocVisitor : public Visitor
{
public:
    explicit AdHocVisitor(std::function<void(const Data&)> f) : f_(std::move(f)) {}
    void visit(const Data& data) override { f_(data); }
private:
    std::function<void(const Data&)> f_;
};

:

AdHocVisitor v([a, &b, this](const Data&) {});
store.visitData(v);
+6

All Articles