c++ - How should I access a function of a container class in a contained class object -


i have following class structure

class containingclass {      int func1(int a);     containedclass containedclassobject; } 

i want access func1 in containedclass objects. best way achieve that?

a naive solution comes mind pass function pointer containedclass's constructor, circular definition, need pass pointer object of containingclass well.

any suggestions?

the containedclass required contract/api/function fulfilled int func1(int) member of containingclass. unless containedclass explicitly requires access instance of containingclass other purposes, access can provided via lambda (or std::bind) , containedclass can have std::function correct signature member holds lambda.

the "trick" here ensure lifetime of objects managed appropriately, i.e. lifetime of containingclass instance @ least long required use in containedclassobject object.

a sample;

#include <functional> class containedclass {     std::function<int(int)> functor_; public:     void setter(std::function<int(int)> functor) { functor_ = functor; } };  class containingclass {     int func1(int a);     containedclass containedclassobject;  public:     containingclass()     {         containedclassobject.setter([this](int a) -> int { return this->func1(a); });     } }; 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -