I have template function "compare" defined as below.
#include<iostream>
using namespace std;
template<typename T>
void compare(const T&a, const T& b)
{
cout<<"Inside compare"<<endl;
}
main()
{
compare("aa","bb");
compare("aa","bbbb");
}
When i instantiate compare with string literals of same length, the compiler doesnot complain. When i do it with literals of different length,it says "error: no matching function for call to compare(const char[3],const char[5])"
I am confused as compare function should be instantiated with character pointer rather than character array. Should not string literals always decay to pointer?
Your example compiles if you change the declaration to:
void compare(const T* a, const T* b)
The reason is that the types of the different sized character arrays are actually different types. If you used sizeof(T)
within the template function the compiler would not know how to resolve the ambiguity. With the above declaration, you are calling a template function with pointer-to-T types, which the compiler will happily resolve as const char*
when passed character strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With