Why is non-const std::array::operator[] not constexpr?

后端 未结 4 519
终归单人心
终归单人心 2020-12-14 16:03

I\'m trying to fill a 2D array on compile time with a given function. Here is my code:

template
struct Table
{
  int data[H][W];
  //std:         


        
4条回答
  •  天命终不由人
    2020-12-14 16:09

    While my first thought was "why would you need a constexpr method on a non-const array"? ...

    I then sat down and wrote a little test to see if the idea made sense:

    #include 
    
    using namespace std;
    struct X{
    
        constexpr X()
        : _p { 0, 1, 2, 3, 4, 5, 6, 7, 9 }
        {
        }
    
        constexpr int& operator[](size_t i)
        {
            return _p[i];
        }
    
        int _p[10];
    };
    
    constexpr int foo()
    {
        X x;
        x[3] = 4;
        return x[3];
    }
    
    
    auto main() -> int
    {
        cout << foo() << endl;
    
        return 0;
    }
    

    It turns out that it does.

    So I'm drawing the conclusion that the committee took the same "obvious" view that I did and discounted the idea.

    Looks to me as if a proposal could be put forward to the committee to change it in c++17 - giving this question as an example.

提交回复
热议问题