samedi 26 décembre 2020

Template argument for std::vector initialization

There is a struct called Matrix with a template argument N and data_ field:

#include <cstddef>
#include <vector>

template <std::size_t N>
struct Matrix {
    std::vector<std::vector<int>> data_{N, std::vector<int>(N)};
};

Why is it not possible to initialize data_ using round brackets?

std::vector<std::vector<int>> data_(N, std::vector<int>(N));

Here's the error:

<source>:6:41: error: unknown type name 'N'
    std::vector<std::vector<int>> data_(N, std::vector<int>(N));
                                        ^
<source>:6:61: error: declaration of 'N' shadows template parameter
    std::vector<std::vector<int>> data_(N, std::vector<int>(N));
                                                            ^
<source>:4:23: note: template parameter is declared here
template <std::size_t N>

Aucun commentaire:

Enregistrer un commentaire