From C++ Primer, I know that for template’s parameter arguments, only two kinds of conversions are performed: one is const conversion, another one is array/function to pointer conversion.
However, when it comes to explicit argument, it seems that everything changes.
Assume we have a template function:
template <typename T>
int compare(const T &a, const T &b)
{
// do comparison
}
If no explicit argument involved, function call like this is illegal:
compare("foo", "foobar");
The weird thing happens (actually, it might not be weird but I do not understand) when we explicitly do:
compare<std::string>("foo", "foobar");
It seems that in the second call, “foo” and “foobar” are converted to std::string, which is controversial.
Is there any special rules for template explicit arguments? Thanks.
In the first case the compiler tries to deduce the type
Tfrom the given parameters. From the first parameter the compiler deduces the typeconst char (&)[4](aka. reference to an array of 4 characters), from the second it getsconst char (&)[7]. The two types don’t match and the compiler can’t figure out whatTshould be.In the second example you explicitly specify that the
Ttemplate parameter should bestd::string. SoTwill bestd::string. The compiler accepts the type you give and checks if the given function parameters match that type. In this case the parameters fit, because"foo"and"foobar"can be implicitly converted tostd::string. (Theconst char[]degrade toconst char*, and then there is a constructor that can construct astd::stringfrom aconst char*)