sz ppeter
sz ppeter

Reputation: 1902

std::basic_string as a parameter of a function template cannot be deduced from const char*

Why does putting std::basic_string as a parameter of a function template will fail to deduce from const char*, but it can be deduced successfully when it is constructed directly?

#include <string>
#include <iostream>
template<class Char/*, class Traits, class Allocator*/>   
                      //^doesn't matter whether the second and third template parameter is specified
void printString(std::basic_string<Char/*, Traits, Allocator*/> s)
{
    std::cout << s;
}
int main()
{
    printString("hello");    //nope
    std::basic_string s{ "hello" };//works
}

I found a relevant post here, but the answers didn't explain the reason behind

Upvotes: 4

Views: 480

Answers (1)

songyuanyao
songyuanyao

Reputation: 172894

Because implicit conversion (from const char* to std::basic_string<char>) is not considered in template argument deduction, which fails in deducing the template parameter Char.

Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.

You can specify the template argument explicitly,

printString<char>("hello");

Or pass an std::basic_string explicitly.

printString(std::basic_string("hello"));

Upvotes: 5

Related Questions