c++metaprogrammingstdarray

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.


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