static_assert on initializer_list::size()

前端 未结 5 1311
执笔经年
执笔经年 2020-12-05 00:29

Why is std::initializer_list<_E>::size not allowable in a static_assert, even though it\'s declared as a constexpr in my libstdc++ (v. 4.6)?

For example, the foll

5条回答
  •  生来不讨喜
    2020-12-05 00:47

    I haven't really figured out what's going on here.

    If I say

    const std::initializer_list li = { 1, 2.5, 3.7, 4.3 };
    static_assert(li.size() == 4, "fail");
    

    I get a complain that 'li' was not declared 'constexper'.

    But if I say

    constexpr std::size_t dSize(std::initializer_list di)
    {
        return di.size();
    }
    

    then

    static_assert(dSize({1, 2.5, 3.7, 4.3}) == 4, "failed");   // works
    

    but

    static_assert(dSize(li) == 4, "failed");
    

    fails with "error: the value of 'li' is not usable in a constant expression"

    This is all with -std=c++11

    So, somehow, an initializer list passed into an arg list can be part of a constant expression, but an initializer list just declared as a const variable can't.

提交回复
热议问题