Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exact number of elements in std::array in function call

I have a function that takes an std::array of given size N

void func(std::array<int,3> x) {
  // do something
}

int main() {
  func({4,4,4}) // works
  func({4}) // works as well
}

I understand why the second call works as well, my question is: is there a way to check at compile time how many arguments I've actually passed?

The background: I don't want to second call to be allowed, I want the user to pass exactly N arguments.

like image 713
Urwald Avatar asked Apr 17 '26 01:04

Urwald


1 Answers

You can make the function more restrictive like this :

#include <type_traits>
    
// let sfinae disable mismatches
template<std::size_t N>
auto func(const int (&v)[N]) -> std::enable_if_t<N==3,void>
{
  // do something
}
        
int main() 
{
    func({4,4,4}); // works
    func({4}); // no longer compiles
}

Demo : https://onlinegdb.com/FHlRINqCZ

like image 193
Pepijn Kramer Avatar answered Apr 19 '26 14:04

Pepijn Kramer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!