I'm currently looking for a solution to give a templated classes’ constructor and function a fixed template according number of arguments N
. My template is of the form template<typename T, unsigned int N>
. The idea is that the following will work:
MyClass<int, 4> object(1, 2, 3, 4);
While the following should fail (and so on):
MyClass<int, 4> object(1, 2, 3);
MyClass<int, 4> object(1, 2, 3, 4, 5);
I'm thinking about something like MyClass(T arg1, ..., T argN){...}
but automatically generated. I only found solutions on how to give a template one or many arguments. But nothing on fixed count.
I Hope somebody can help me. Thank You in advance!
You can add a constraint to the overload, such as
template <typename T, std::size_t N>
struct MyClass {
// pre-C++20
template <typename... Args, std::enable_if_t<sizeof...(Args) == N, int> = 0>
MyClass(Args&&... args) { /* ... */ }
// or alternatively, post-C++20,
template <typename... Args>
requires (sizeof...(Args) == N)
MyClass(Args&&... args) { /* ... */ }
};
Note that in the case N == 1
then in a couple of cases these templates will be preferred over the automatically generated copy constructor. If this is a potential issue then you will need to further constrain the templates to prevent this case. Here is an example of how you might do so.
If you don't need to use SFINAE to discern between other constructors, you could instead use static_assert
as well:
template <typename... Args>
MyClass(Args&&... args) {
static_assert(sizeof...(Args) == N);
// ...
}