Search code examples
c++templatespointerstype-deduction

How does the type deduction work for string literals in C++?


In C++ if I have a generic function:

template <typename T>
void func(T& s)
{
    std::cout << "in generic\n";
    std::cout << typeid(s).name();
}

T will get deduced to typeid(s).name().

But how come if I do:

func("test");

That generic function works, but this one doesn't:

void func(const char*& s)
{   
    std::cout << "in overloaded\n";
    std::cout << typeid(s).name();
}

I know that it'll work if I change const char*& to const char* or const char* const&in the overloaded function's signature, and that if I want to pass an argument to the overloaded function it must be non-temporary. I just don't understand what happened to T&, isn't it supposed to turn into const char*& after the deduction?


Solution

  • String literals are arrays of const characters. So in the case of the template function called like this:

    func("test");
    

    T is deduced as char const[5]. And s is a reference to the string literal, and its type is char const (&)[5]. That is, a reference to an array of 5 const char.