Search code examples
c++templatesc++20metaprogramming

How to expand this C++ template parameter package


I want to expand the template parameter package into a 2-dimensional array, but I don't know how to achieve it

Because the elements of the matrix class are usually floating point decimals, but this is only supported by the syntax after C++20

template<int Row, int Col, typename T = float>
struct MATRIX
{
    template<T... Args>
    MATRIX(Args... nums) : aNumbers{ (nums, 0)... }// this is error
    {
        //aNumbers = { (nums, 0)... };
    }

    T aNumbers[Row][Col];

I tried several syntaxes, but none of them compiled. I want to achieve a constructor with variable length template parameters


Solution

  • You need to decide whether you want the elements be non-type template arguments (this would require c++20) or ordinary arguments to the constructor. The latter is rather straightforward:

    template<int Row, int Col, typename T = float>
    struct MATRIX
    {
        template <typename...X>
        MATRIX(X... nums) : aNumbers{ nums... }
        {
    
        }
    
        T aNumbers[Row][Col];
    };
    
    int main() {
        MATRIX<3,3,double> m{1.,2.,3.,4.,5.,6.,7.,8.,9.};
    }
    

    Only to make sure that X... equals T, something extra is needed. Though, one step at a time, and I consider this beyond the scope of the question.

    In your code:

    template<T... Args>
    MATRIX(Args... nums)
    

    Args is a non-type template argument for the constructor, hence Args...nums makes no sense.