c++templatesc++17template-argument-deduction

Template class and automatic deduction


I've something like that:

struct Relay
{
    int pin;
    bool state;
};

template<typename... Relays>
class RelayArray
{
private:
    Relay array[sizeof...(Relays)];
public:
    RelayArray(Relays... relays) : array{relays...}
    {}
};

RelayArray<Relay, Relay, Relay> myRelayArray{{2, true}, {4, false}, {6, true}};
RelayArray myRelayArray2{Relay{2, true}, Relay{4, false}, Relay{6, true}};

I'd like to be able to declare myRelayArray without specifying the number of elements, nor each type, something like this:

RelayArray myRelayArray{{2, true}, {4, false}, {6, true}};

Somehow, I don't get it to write ! The code should be in C++17 (or less) and without initializer_list (not available for avr/arduino c++!).

Thx for your help.


Solution

  • The problem is that {2, true} does not have any type. Since you're not allowed to use initializer_list, other options are using std::array, std::vector etc.

    If you're not allowed to use std::array, you can use old c-style arrays as shown below. It is trivial to change this to use std::array and is left as an exercise:

    struct Relay
    {
        int pin;
        bool state;
    };
    
    template<std::size_t N>
    class RelayArray
    {
    private:
        Relay array[N]; //or std::array<Relay, N>
    public:
        RelayArray(const Relay(&ref)[N]) 
        {}
    };
    
    RelayArray myRelayArray{{{2, true}, {4, false}, {6, true}}}; //works 
    

    Demo