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

wrapping templated function call in another function call

Anyone know if it is possible to do something similar to the following:

void my_inner_func(int i, double d, ...) { 
    // do stuff here
}

template <typename Func, typename... Args>
void my_outer_func(Func&& f,Args&&... args){
    // do other stuff here, put this inside loop, etc
    f(std::forward<Args>(args)...);
}

template <typename OuterFunc,typename InnerFunc,typename... Args>
void func(OuterFunc&& outer, InnerFunc&& inner, Args&&...args) {
    outer(std::forward<InnerFunc>(inner),std::forward<Args>(args)...);
}

Where the calling code might look something like this:

func(my_outer_func, my_inner_func, 1, 2.0, ...);

The issue that I am running into is that the type of the OuterFunction cannot be deduced. I’ve tried a bunch of different things including converting func to a functor and making OuterFunc a template template parameter.

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 :

It works if you make my_outer_func a function object rather than a function:

struct my_outer_func {
    template <typename Func, typename... Args>
    void operator()(Func&& f,Args&&... args) const {
        // do other stuff here, put this inside loop, etc
        f(std::forward<Args>(args)...);
    }
};

Then:

func(my_outer_func(), my_inner_func, 1, 2.0);

If you don’t like the parentheses at the call site, you can remove them if you create a global struct instance instead:

struct {
    template <typename Func, typename... Args>
    void operator()(Func&& f,Args&&... args) const {
        // do other stuff here, put this inside loop, etc
        f(std::forward<Args>(args)...);
    }
} my_outer_func;
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