CodingMadeEasy
CodingMadeEasy

Reputation: 2337

Create Functions that takes variable amount of parameters and data types

I know this question might be a little weird but the creators of C++ made it so that whenever we create a function in C++ we can specify what we want our parameters to be for example we can create a function like this:

void function(int test); 

As well as we can create a function like this:

void function(std::string test); 

How do I re-create that effect? I'm in the midst of creating a delegate class that works somewhat like CA# delegates but I'm having a problem when it comes to the parameters. I don't know what type of variable they'll want to store in the delegate so I have to implement something that they can specify which variable types they'll be using. Something like this:

Delegate myDelegate(std::string, int, float);

Is it possible to do that? I've looked into variadic functions but you have to know which type to cast it too. I know I could have indicators like "%d and %s" just like the printf function but is there a way to implement it so that it accepts the object names rather than a indicator? I hope this is simple to understand.

Upvotes: 0

Views: 170

Answers (2)

ironMover
ironMover

Reputation: 107

A simple solution would just be function overloading. Also, if future code maintenance is required, it would provide the most clarity (at least that is my hunch). Anyway, this would produce exactly the behavior you are describing.

Upvotes: 0

Dietmar Kühl
Dietmar Kühl

Reputation: 153955

You can use variadic argument lists. Here is a quick example:

#include <algorithm>
#include <iostream>
#include <vector>
#include <functional>

template <typename... T>
class Delegate {
    std::vector<std::function<void(T...)>> d_delegates;
public:
    template <typename F>
    void add(F&& f) { this->d_delegates.push_back(std::forward<F>(f)); }

    template <typename... S>
    void operator()(S... args) const {
        std::for_each(this->d_delegates.begin(), this->d_delegates.end(),
                      [&](std::function<void(T...)> const& f){ f(args...); });
    }
};

void f1(int i) { std::cout << "f1(" << i << ")\n"; }
void f2(int i, double d) { std::cout << "f2(" << i << ", " << d << ")\n"; }

int main() {
    Delegate<int> d1;
    d1.add(f1);
    d1(17);

    Delegate<int, double> d2;
    d2.add(f2);
    d2(42, 3.14);
}

Upvotes: 1

Related Questions