Using std::extent on std::array

后端 未结 4 1728
名媛妹妹
名媛妹妹 2021-01-13 08:21

I have a templatized function and I want to static_assert that it\'s type has a size of three. This code illustrates what I\'m trying to do, but doesn\'t work:<

4条回答
  •  日久生厌
    2021-01-13 09:15

    std::extent is defined for built-in arrays. For std::array use std::tuple_size instead. I don't know some trait that works on both, but it's easy to write one:

    template
    struct array_size : std::extent { };
    
    template
    struct array_size > : std::tuple_size > { };
    

    and here's your foo, corrected/generalized (live example):

    template < typename T >
    void foo( T&& param )
    {
        using U = typename std::remove_cv::type>::type;
        static_assert( 3 == array_size::value, "param must have a size of 3" );
    }
    

    Prefer a universal reference T&& param, otherwise only lvalues can be used.

提交回复
热议问题