std::basic_string 作为函数模板的参数不能从 const char* 推导出来

sz *_*ter 4 c++ templates implicit-conversion template-argument-deduction

为什么std::basic_string作为函数模板的参数 put 会推演失败const char*,而直接构造却可以推演成功?

#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
}
Run Code Online (Sandbox Code Playgroud)

我在这里找到了相关帖子,但答案没有解释背后的原因

son*_*yao 5

因为模板参数推导中没有考虑隐式转换(from const char*to ) ,导致模板参数推导失败。std::basic_string<char>Char

类型推导不考虑隐式转换(除了上面列出的类型调整之外):这是稍后发生的重载解析的工作。

您可以显式指定模板参数,

printString<char>("hello");
Run Code Online (Sandbox Code Playgroud)

或者明确地传递一个std::basic_string

printString(std::basic_string("hello"));
Run Code Online (Sandbox Code Playgroud)