The following code compiles fine:
template<typename T>
void f(const T &item) { return; }
int main()
{
f("const string literal");
}
Compilation succeeded at ideone : http://ideone.com/dR6iZ
But when I mention the return type, it doesn’t compile:
template<typename T>
T f(const T &item) { return item; }
int main()
{
f("const string literal");
}
Now it gives error:
prog.cpp:6: error: no matching function for call to ‘f(const char [21])’
Code at ideone : http://ideone.com/b9aSb
Even if I make the return type const T, it doesn’t compile.
My question is :
- Why does it not compile?
- What does the return type has to do with the error and the function template instantiation?
You cannot return an array from a function, so template instantiation fails, and there’s no matching function.
You get this particular error because of SFINAE – It’s not really an error that the compiler cannot instantiate your function, it is an error that there’s no matching function.
You can return a reference to an array – returning
T const &will work.EDIT: In response to comments:
First, this is actually a decent example of SFINAE.
When the compiler compiles this, it’ll first try to instantiate the templated f, to create an exact match for the type
const char [3]. This fails, because of the mentioned reasons. It’ll then select the inexact match, the plain function, and in the call decay theconst char [3]to aconst char *.