Search code examples
c++templates

Why is comparison working in template for different sizes of const char(&)[N]?


This is a compile time error for compare1 I understand the reason.

But why doesn't it fail for compare2?

#include <iostream>
#include <vector>
#include <string>
using namespace std;


template<typename T1, typename T2>
const T1& compare1(const T1& a, const T2& b) //Can be error: if a and b of different array sizes.
{
     return a < b ? a : b;
}

template<typename T1, typename T2>
bool compare2(const T1& a, const T2& b) //Why is differenent array size error not applicable here?
{
     return a < b ? a : b;
}

int main()
{ 
    compare1("hello", "world"); //sucess
    compare1("hello", "worldx"); //fail as expected
    compare2("hello", "worldx"); // passed which is not expected.
}

Edit: Question is why there is no error for compare2.

<source>: In instantiation of 'const T1& compare1(const T1&, const T2&) [with T1 = char [6]; T2 = char [7]]':
<source>:21:13:   required from here
   21 |     compare1("hello", "worldx");
      |     ~~~~~~~~^~~~~~~~~~~~~~~~~~~
<source>:10:19: error: invalid initialization of reference of type 'const char (&)[6]' from expression of type 'const char*'
   10 |      return a < b ? a : b;
      |             ~~~~~~^~~~~~~

Solution

  • why there is no error for compare2.

    Because in case of compare2 the return type is bool and the operands a and b in the return statement are both arrays which can decay to pointers to char which in turn can be converted to bool.

    Gcc and msvc even gives warning saying:

    warning C5056: operator '<': deprecated for array types
    

    Baiscally, it compiles for the same reason the following compiles:

    const char a[] = "hello";
    const char b[] = "worldx";
    bool r = a < b ? a : b;