c++classtemplatesvariadic-templates

How to recursively use variadic templates with classes?


I've tried to recursively define variadic template classes, similar to various examples I saw for functions:

class Network
{
public:
    template<int m>
    const void forward(const Matrix<m, 1> &Input, Matrix<m, 1> &Output)
    {
        copy(Input,Output);
    }
};

template <typename L, typename... Ls>
class Network
{
public:
    L layer;
    Network<Ls...> fnet;
    const void forward(const Matrix<L::Is, 1> &Input, Matrix<L::Os, 1> &Output)
    {
        Matrix<L::Os, 1> temp;
        layer.forward(Input, temp);
        fnet.forward(temp, Output);
    }
};

However this does not work since classes cannot be overloaded in the same way that functions can. So how do you "unpack" a variadic class template?


Solution

  • Network will eventually have an empty pack so you need to specialize for that and for the general case.

    template<class...>
    class Network;
    
    template<>
    class Network<>
    {
    public:
        template<int m>
        void forward(const Matrix<m, 1> &Input, Matrix<m, 1> &Output)
        {
            copy(Input, Output);
        }
    };
    
    template <typename L, typename... Ls>
    class Network<L, Ls...>
    {
    public:
        L layer;
        Network<Ls...> fnet;
        void forward(const Matrix<L::Is, 1> &Input, Matrix<L::Os, 1> &Output)
        {
            Matrix<L::Os, 1> temp;
            layer.forward(Input, temp);
            fnet.forward(temp, Output);
        }
    };