Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading