Getting the number of elements in std::array at compile time

前端 未结 4 960
礼貌的吻别
礼貌的吻别 2021-02-06 23:45

Is the following a valid C++ code, and why not?

std::array a1;
std::array a2;

It doesn\'t compile

4条回答
  •  执念已碎
    2021-02-07 00:00

    array::size() is constexpr, but you can't use it in this way because a1 isn't a constexpr value. Additionally, it can't be constexpr because string isn't a literal type.

    However, you can work around this if you want, by deducing the size_t template parameter. Example:

    #include 
    #include 
    #include 
    using namespace std;
    
    template
    struct array_size;
    template
    struct array_size > {
        static size_t const size = N;
    };
    
    array a1;
    array::size> a2;
    
    int main() {
        cout << a2.size() << endl;
    }
    

提交回复
热议问题