Using std::extent on std::array

后端 未结 4 1725
名媛妹妹
名媛妹妹 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 08:51

    I can't think of a way to write a single function that handles both, but this is what overloading is for.

    template 
    void check_array_size( T (&)[Bound] )
    {
        static_assert(Bound == N, "incorrect array size");
    }
    
    template 
    void check_array_size( const std::array& )
    {
        static_assert(Bound == N, "incorrect array size");
    }
    
    template 
    void check_array_size( ... )
    {
        static_assert(N<0, "argument is not an array");
    }
    
    template 
    void foo(T& param)
    {
        check_array_size<3>(param);
        // actual function implementation...
    }
    

提交回复
热议问题