简体   繁体   中英

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

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM