Why isn't std::array::size static?

后端 未结 6 2051
执念已碎
执念已碎 2020-12-15 16:57

The size of std::array is known at compile time, but the size member function isn\'t static. Is there any reason for that? It\'s slightly inconvenient not to be

6条回答
  •  难免孤独
    2020-12-15 17:21

    In my opinion it does not make sense to make the size member function static insofar as it provides no added value. It is possible to make it static, but you gain nothing from it.

    The way the array class is designed, you can query the size of a given array object without explicitly knowing/remembering its exact type (which includes its size) at that location where you need the size. This is a convenience, and it removes the opportunity to make copy/edit errors. You can write code like this:

    std::array blah;
    // 50 lines of code
    do_something_with(blah.size()); // blah knows its size
    

    As you can see, at the location where I'm consuming the array's size, I don't actually remember what it was, but my code will work anyway, regardless of what the value actually is, and regardless whether maybe one day I change the array's type to be a different size.
    Since the size function merely returns a template parameter, the compiler can trivially prove that the return value is a compile-time constant and optimize accordingly too (the function is also constexpr, so you can also use the return value as template parameter or enumeration).

    Now what will be different if we make the size member function static?

    If size was a static function, you could still use the static member function in the exact same way (that is, on an object instance, in a "not static way"), but that would be "cheating". After all, this is something that already works anyway, whether the member is static or not.
    Further, you now have the possibility of invoking the member function without an object instance. While this seems like a good thing at first glance it really is no advantage at all for the array class template (...where the returned size is a template parameter).

    In order to call a member function without an object (that is, in a "static member function way"), you must properly qualify the function with the class name and its proper template parameters.
    In other words, you must write something like:

    std::array blah;
    // 50 lines of code
    do_something_with(std::array::size()); // I must tell size what to return
    

    Now what have we gained from calling the size function? Nothing at all. In order to call the function, we needed to provide the correct template parameters, which includes the size.

    That means no more and no less than that we must supply the information that we wish to query. Calling the function doesn't tell us anything we didn't already know.

提交回复
热议问题