Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template instantiation error

Tags:

c++

templates

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?

like image 531
chappar Avatar asked Jun 27 '09 04:06

chappar


1 Answers

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.

like image 61
Greg Hewgill Avatar answered Sep 23 '22 11:09

Greg Hewgill