Jichao Jichao - 3 months ago 15
C++ Question

reference type conversion in template function?

#include <iostream>
const char* max(const char* a, const char* b) {
return strcmp(a,b) < 0 ? b : a;
}

template <typename T>
const T& max(const T& a, const T& b, const T& c)
{
return max(max(a,b),c);
}

int main()
{
char* a = "abc";
char* b = "cde";
char* c = "def";
const char* r = max(a,b);
char* s = max(a,b,c);
return 0;
}


cannot compile:


max3a.cpp:9:12: error: invalid conversion from 'const char*' to
'char*' [-fpermissive]

return max(max(a,b),c);



If I change the template function to

template <typename T>
const T& max(const T& a, const T& b, const T& c)
{
(const T)return max(max(a,b),c);
}


then it compiles successfully.

If
T
is
char *
, the type of
max(max(a,b),c)
is
const char*
, which is
const T
. Why?

Answer

If T is char *, then the type of max() is char *const&, not char const *.

In other words, your function is returning a reference to a constant pointer to char, not a pointer to const char.