Say I have the following template class:
template<int R> class dummy{
public:
// functions
private:
int arr[R];
};
Is it possible to create a constructor that accepts exactly R number of parameters that are to be used to initialize the array?
Something used like this:
dummy<3> a(1,2,3); // where array[0] is set to 1, array[1] is set to 2, and so on...
I know how to achieve the same result with this:
template<int R> class dummy{
public:
dummy(const int(&list)[R]){
for (int i = 0; i < R; i++) arr[i] = list[i];
}
private:
int arr[R];
};
Then use it:
dummy<3> a({1,2,3}); // OK
dummy<3> b({1,2}); // also OK but arr[2] will be set to 0
dummy<3> c({1,2,3,4}); // compile-time error
The issue is I want a compile time guarantee that the list being passed is exactly the size R, not bigger, not smaller. The compiler for the above code will complain if the list is larger, but not if smaller.
I saw this answer but the size there is automatically determined by the function call and the hardcoded value of 3 is part of the assertion. I can't use static_assert because R will always be the value set by the class initialization (e.g., dummy<3> sets R=3 and the constructor call will fill the list with 0s if it is smaller than 3).
How to guarantee the number of passed arguments is exactly R at compile time?
The
static_assert()works well if you make the constructor parameterized. Working example: https://godbolt.org/z/dcP683cdh