Search code examples
c++c++11header-filesdeclarationstdbind

std::bind header file declaration


I want to create a std::bind for a function in a cpp file other than my main one, and also in a different namespace. The problem I'm having is how to declare said function in the header file since the binding itself depends on a variable not available to main.cpp.

It is something like this:

function.cpp

#include "function.h"
namespace A{
    void function(int i) { ... }   // supposed to be invisible from outside
    namespace A1{
        int varA1;
        auto func = std::bind(A::function, varA1);
    }
    namespace A2{
        int varA2;
        auto func = std::bind(A::function, varA2);
    }
}

function.h

namespace A{
    namespace A1{
        auto func();
    }
    namespace A1{
        auto func();
    }
}

I'm aware the above example does not work, but how do I change the header file in order to fix it?


Solution

  • The only solution i can see is to use an std::function, since it is pretty much the only object that can take a bind object with a defined type.

    So, if i read your code correctly, it should return something like:

    std::function<void()> func();
    

    Just to be sure, you are aware that you are declaring functions in your header? To match it, your cpp file should be more like:

    namespace A1{
        std::function<void()> func() {
            int varA1;
            return std::bind(A::function, varA1);
        }
    }
    

    Also notice something important, a call to std::bind in your case will copy your variable. So if you want your resulting function to see the changes to your variables after being created, you should give it a reference:

    std::bind(A::function, std::cref(varA1));