static_assert on initializer_list::size()

前端 未结 5 1299
执笔经年
执笔经年 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:59

    "Initializer lists" are just horrible kludges.

    Don't:

    #include 
    
    template
    void Dont(std::initializer_list list) { // Bad!
        static_assert(list.size() == 3, "Exactly three elements are required.");
    }
    
    void Test() { Dont({1,2,3}); }
    

    Do:

    template
    void Do(const T(&list)[N]) { // Good!
        static_assert(N == 3, "Exactly three elements are required.");
    }
    
    void Test() { Do({1,2,3}); }
    

提交回复
热议问题