2

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?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118

1 Answers1

0

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));
Adrien Hamelin
  • 395
  • 3
  • 9
  • Yes, the header declaration is to make the function available for, say, main.cpp. Anyway, I understood that i have to "wrap" the 'std::bind' inside a 'std::function'. Isn't there a way to make the binding itself visible outside the cpp file? I have also considered a functor instead of bindings. Is there any major performance difference between them? – Misora Grilo Nov 24 '15 at 17:23
  • You could use it like that: `using Type = decltype(std::bind(function, 1));` if you are always using the same function and parameters types, but it requires a declaration of the function before. If you do not want to declare it before, you need to add an abstraction that will take some resources at runtime (such as `std::function`). A functor will not be as efficient as the example before, but i suppose should be better than `std::function`. Only one way to be sure though: measure. – Adrien Hamelin Nov 24 '15 at 22:45