Search code examples
c++arraysstringtemplatestemplate-argument-deduction

Passing c-style string to a template function


I can't understand the following behavior of my program. As far as I know, template argument deduction allows only 1) array- or function-to-pointer conversions or 2) const conversions. The program below should result in a compilation error. However, if I pass two c-style strings of equal length, it compiles. What is causing this behavior?

#include <iostream>
#include <type_traits>
  
  
template <typename T>
int compare(T& x, T& y) {
  return 1;
}
  
  
int main() {
   compare("abc", "abc"); // no compilation error
}    

Solution

  • You can use cpp-insights to have a look at what is going on here. You will see your generated function signiture is:

    template<>
    int compare<const char[4]>(const char (&x)[4], const char (&y)[4])
    {
      return 1;
    }
    

    This is because the type of the 2 literals are both const char[4] and you are taking a reference to them in your signature. The reason that it ends up being const& is because your type brings the const with it. The same way that this works:

    template <typename T>
    int foo(T& x) {
      return 1;
    }
    
    ...
    
      int a = 5;
      const int& r_a = a;
      foo(r_a);