Is there a way to enforce full initialization of std::array

后端 未结 3 1621
耶瑟儿~
耶瑟儿~ 2021-01-02 05:18

I am using std::array (N is a fixed template-variable).

#include
template
struct A{
   size_t fun         


        
3条回答
  •  一个人的身影
    2021-01-02 05:59

    You can enforce this by using parameter pack, but with a bit different syntax:

    #include 
    
    template
    struct A{
       template
       size_t function(T&&... nums)
       {
         static_assert(sizeof...(nums) == N, "Wrong number of arguments");
         std::array arr = { std::forward(nums)... };
         return arr[N-1];
       }
    };
    
    int main(){
       A<5> a;
       a.function(1,2,3,4,5); // OK
       a.function(1,2,4,5);   // Compile-time error
    }
    

    But, I think there is no good way to enforce that in compile time. I would just use assert(il.size() == N) in production code to check size of initializer list.

提交回复
热议问题