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):
class Visitor
{
virtual void visit(const Data& data) = 0;
}
class DataStore
{
void visitData(Visitor& visitor) { }
}
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);
}
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.