Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to passing one or more (undefined number) parameters to a function?

I'm writing a wrapper class for wiringPi. I would like to be able to manipulate more than one LED, by calling the function once, by passing one or more parameters to the function. The number of passed parameters should not be limited, i.e., it can be 1, 2, 3, or more. Here is my current function:

typedef enum{LED1 = 12, LED2 = 13, LED3 = 14, LED4 = 15}LED;

void Led::on(LED led)
{
    digitalWrite(led, HIGH);
}

Can I do this? and how?

I think I can use overloading for this but what if the number of parameters is undefined (i.e., it can be 1 or 7)?

like image 660
Salahuddin Avatar asked Mar 07 '23 23:03

Salahuddin


2 Answers

A bitfield?

If you have a little number of leds and you define their values using different bits

typedef enum {LED1 = 1, LED2 = 2, LED3 = 4, LED4 = 8};

or better (to be sure tu use only power of two values), as suggested by user2079303 (thanks!),

typedef enum {LED1 = 1 << 0, LED2 = 1 << 1, LED3 = 1 << 2, LED4 = 1 << 3};

you can pass a or-value of leds to Led::on()

on(LED1 | LED2 | LED4);

and check, inside on(), single bits

void Led::on (int leds)
 {
   if ( 0 != (leds & LED1) )
    /* do something for LED1 */;

   if ( 0 != (leds & LED2) )
    /* do something for LED2 */;

   // ...
 }
like image 174
max66 Avatar answered Mar 13 '23 06:03

max66


Example using variadic. This is likely the most efficient way to do this as all the work is done in compile time.

enum LED {LED1 = 12, LED2 = 13, LED3 = 14, LED4 = 15};
constexpr const int HIGH = 1;
void digitalWrite(LED, int);

template<class... LED>
void on(LED... leds)
{
    (digitalWrite(leds, HIGH), ...);
}

void foo() {
    on(LED1, LED2, LED3);
    on(LED4);
}

https://godbolt.org/g/b22y5N

Note: you need c++17 for above syntax


C++11 Compatible version:

enum LED {LED1 = 12, LED2 = 13, LED3 = 14, LED4 = 15};
constexpr const int HIGH = 1;
void digitalWrite(LED, int);

void on(LED leds)
{
    digitalWrite(leds, HIGH);
}

template<class... LEDs>
void on(LED led, LEDs... leds)
{
    on(led);
    on(leds...);
}

void foo() {
    on(LED1, LED2, LED3);
    on(LED4);
    on(LED1, LED2);
}

https://godbolt.org/g/Js13vi

like image 43
balki Avatar answered Mar 13 '23 04:03

balki