user3567603
user3567603

Reputation:

Call function pointers via variadic template as template argument

I want to pass functions (known before compile time) via template (not via function) to a class. In the class I want to call those functions after each other. The functions always have the same type (in this case returns void and pass no arguments). Later on I want to pass functions like this: void foo(uint16_t arg); I've tried two things but I cannot find a solutions.

typedef void(*decodeFunct)(void);

template <uint8_t pin, decodeFunct... functions>
class CIRLremote{
public:
    CIRLremote(void){
        // empty
    }
    void begin(void){
        // call all decode functions
        //functions... ();
        call(functions...);
    }

    void call(decodeFunct f){
        f();
    }
};

Upvotes: 1

Views: 187

Answers (1)

danielschemmel
danielschemmel

Reputation: 11126

You can easily write a function that calls all its arguments by always calling its first argument and recursively invoking itself with the remaining arguments. An overload for the empty parameter list provides an anchor to the recursion:

#include <utility>

inline void call() { }

template<typename T, typename... V>
inline void call(T&& t, V&&... v) { t(); call(std::forward<V>(v)...); }

If you call this exactly as your example is doing, it will just work.

Note that the argument types are not fixed, so you can call it with any functor, not just function pointers.

Modifying it to suit any similar use case (e.g. distribute one argument, pass one argument per functor, aggregate the result, etc. pp.) is pretty simple.

Upvotes: 0

Related Questions