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

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 :

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

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);
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