Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass a function pointer with variable parameters as an argument in C++

I’m trying to pass a function, with a variable amount of parameters, as an argument to my function baz(). I’m not really sure how to go about doing this, but hopefully the example I’ve provided below shows my current thought-process.

#include <iostream>

template<typename... Ts>
void foo(void (*func)(Ts...)){
    func(Ts...);
}

void bar(int a, int b, std::string c){
    std::cout << "Test a: " << a << " Test b: " << b << " Test c: " << c << "\n";
}

void baz(int x, int y){
    std::cout << x+y << "\n";
}

int main()
{
    foo(&bar, 10, 20, "Hello!"); // Expected: "Test a: 10 Test b: 20 Test c: Hello!"
    foo(&baz, 2, 2);             // Expected: "4"
    // main.cpp:13:12: error: expected primary-expression before ‘...’ token

    return 0;
}

Any help is greatly appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can pass a function type

#include <iostream>

template<typename Fn, typename ... Ts>
void foo( Fn&& func, Ts...ts ){
    func(ts...);
}

void bar(int a, int b, std::string c){
    std::cout << "Test a: " << a << " Test b: " << b << " Test c: " << c << "\n";
}

void baz(int x, int y){
    std::cout << x+y << "\n";
}

int main()
{
    foo(&bar, 10, 20, "Hello!"); // Expected: "Test a: 10 Test b: 20 Test c: Hello!"
    foo(&baz, 2, 2);             // Expected: "4"
    return 0;
}

Produces

Program stdout
Test a: 10 Test b: 20 Test c: Hello!
4

Godbolt: https://godbolt.org/z/beMv6a9a4

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading