1

I have several c functions that do pretty much the exact same thing except for functions on one line. I want to replace all of these functions with one function that I can pass as function pointer for that one line:

Func1(type parameter);

Func2(type1 parameter1,type2 parameter2);

FuncFunc(FunctionPointer functionPointer){
    funcVar;
    ...
    functionPointer(funcVar,....);
    ...
}

int main(){
    FuncFunc(Func1);

    FuncFunc(Func2(,type2Object));
}

Is there anyway I can do this in C++?

  • 2
    This can certainly be done in C++. However, your question is somewhat unclear. "several c functions that do pretty much the exact same thing except for functions on one line" -- this is completely unparsable. Can you extrapolate and give an example. – Sam Varshavchik Aug 18 '16 at 02:39

1 Answers1

2

It's not clear what you are trying to achieve, but here is an example how your code may me translated into valid C++. First, let's define your Func with maximum number of arguments:

template<typename T1, typename T2>
void Func(T1 par1, T2 par2) {
        std::cout << par1 << " " << par2 << std::endl;
}

Then we should make FuncFunc accept any function you want:

template<typename ...T>
void FuncFunc(const std::function<void(T...)>& fPtr) {
        std::string funcVar = "Foo!";
        fPtr(funcVar);
}

or easier to use variant:

template<typename F>
void GuncFunc(const F& fPtr) {
        std::string funcVar = "Foo!";
        fPtr(funcVar);
}

and finally use FuncFunc:

auto Func1 = std::bind(Func<float, std::string>, 3.14f, std::placeholders::_1);
auto Func2 = std::bind(Func<std::string, int>, std::placeholders::_1, 42);
FuncFunc(std::function<void(std::string)>(Func1));
FuncFunc(std::function<void(std::string)>(Func2));
return 0;

or GuncFunc:

// Using std::bind
GuncFunc(std::bind(Func<float, std::string>, 3.14f, std::placeholders::_1));
GuncFunc(std::bind(Func<std::string, int>, std::placeholders::_1, 42));

// Or using lambdas:
GuncFunc([](std::string s){Func<float, std::string>(3.14f, s);});
GuncFunc([](std::string s){Func<std::string, int>(s, 42);});

Choosing std::bind or lambdas seems to be out of scope of your question, but you may found something useful here, there or in this question.

Anyway, very likely you will need lambdas, std::function, std::bind or variadic templates.

Community
  • 1
  • 1
Sergey
  • 7,985
  • 4
  • 48
  • 80
  • 1
    You could also use (and probably should prefer) lambdas instead of `std::bind` – qxz Aug 18 '16 at 03:53