Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Folding Expression to initialize an array?

I come across with a weird problem in which MSVC doesn't let me to use fold expression to initialize an array in the following:

#include <iostream>

template <typename T, std::size_t ...dims>
class Matrix {
public:
    void print()
    {
        std::cout << (... + dims) << '\n';
    }
    
    T matrix[(... + dims)];      // <-- error C2059: syntax error: '...'
};

int main()
{
    Matrix<int, 3, 3, 3> m;
    m.print();
    Matrix<int, 3, 2, 1> n;
    n.print();
    return 0;
}

Here is the errors:

(10): error C2059: syntax error: '...' (11): note: see reference to class template instantiation 'Matrix' being compiled (10): error C2238: unexpected token(s) preceding ';'

I tried GCC and everything just worked perfectly fine!

Is there any workaround to use fold expression directly to initialize an array with MSVC?

Thank you so much guys!

like image 520
Nima Ghorab Avatar asked Dec 16 '21 09:12

Nima Ghorab


1 Answers

This looks like a bug in the MS compiler. As with any bug of such kind, it's hard to tell what exactly goes wrong unless you know MS compiler internals.

A workaround is the introduction of an intermediate member variable:

template<typename T, std::size_t... dims>
class Matrix {
    // ...
    static constexpr std::size_t my_size = (... + dims);
    T matrix[my_size];
};

or a static member function:

    static constexpr std::size_t my_size() { return (... + dims); }
    T matrix[my_size()];
like image 149
Evg Avatar answered Oct 27 '22 17:10

Evg