Search code examples
c++11friendstd-function

std::function and friend function


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?


Solution

  • 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();
    }