0

In this example, I have a pointer of function (std::function) as an attribute of my class. So I can associate any function of the form void myFunction(void) to my class.

#include <iostream>
#include <functional>

class Example{
private:
    int variable=4;
public:
    std::function<void(void)> myNonMemberFunction;
    Example(void){
    }
    Example(std::function<void(void)> MyNonMemberFunction){
        myNonMemberFunction=MyNonMemberFunction;
    }
};

void PrintPlop(){
    std::cout<<"plop"<<std::endl;
}

int main() {
    Example example(PrintPlop);
    example.myNonMemberFunction();
}

Now, I want to do the same but with a function which has accessed to the class attribute like a friend function or a class-member function. How can I do this?

1 Answers1

0

So you want any function you pass to the constructor become a friend?

In the strict sense it is impossible, because the access level (friend or not) is a compile-time issue, and which value is passed to the constructor, generally speaking, is determined only in run-time.

So you either declare all the relevant functions as friends (why not just make them methods in this case?) or pass the private members to them as additional parameters. Like this:

class Example{
private:
    int variable=4;
    std::function<void(int)> myNonMemberFunction;
public:
    Example(void){
    }
    Example(std::function<void(int)> MyNonMemberFunction){
        myNonMemberFunction=MyNonMemberFunction;
    }
    void callMyNonMemberFunction() {
      myNonMemberFunction(variable);
    }
};

void PrintPlop(int v){
    std::cout<<"plop"<< v << std::endl;
}

int main() {
    Example example(PrintPlop);
    example.callMyNonMemberFunction();
}
aparpara
  • 2,171
  • 8
  • 23
  • Thanks, it has solved my problem. I have done this, because I want to customize the way to manipulated the different attributes of my class. For this, I have modified std::function to std::function and it works. – Baptiste Nguyen Apr 20 '19 at 19:45
  • @BaptisteNguyen, glad to know it! And please note that "thanks" here is expressed by upvoting (see the triangle at the upper left corner of my answer? klick it!) and by marking the answer as the right. – aparpara Apr 20 '19 at 19:50