get the size of `std::initializer_list` at compile time

后端 未结 1 1682
别那么骄傲
别那么骄傲 2021-01-01 08:00

I am trying to implement the reshape function of fortran with C++(11/14) and I designed a function. This function accepts two std::initializer_list

相关标签:
1条回答
  • 2021-01-01 08:37

    Maybe its a bad idea to use std::initializer_list?

    I think so. Consider

    std::initializer_list<int> t;
    std::initializer_list<int> a = {1,2,3};
    std::initializer_list<int> b = {2,3};
    if (rand() > 42)
        t = a;
    else
        t = b;
    auto reshaped_array = forreshape({1,2,3,4,5,6}, t);
    

    In the above example, it's just impossible to know t.size() at compile time.

    But you can ask the compiler to deduce the length of an initializer list by using a reference to C-style array, thanks to CWG 1591.

    The definition of forreshape would look like:

    template<int D, typename T>
    auto forreshape(const std::initializer_list<T> & values, const int (&shape)[D])
    {
        // use D...
    }
    
    0 讨论(0)
提交回复
热议问题