std::basic_string 作为函数模板的参数不能从 const char* 推导出来
std::basic_string as a parameter of a function template cannot be deduced from const char*
为什么把std::basic_string
作为函数模板的参数从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
}
我找到了一个相关的post ,但是答案没有解释背后的原因
因为在template argument deduction中没有考虑隐式转换(从const char*
到std::basic_string<char>
),这导致模板参数推导失败Char
。
Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.
您可以明确指定模板参数,
printString<char>("hello");
或显式传递 std::basic_string
。
printString(std::basic_string("hello"));
为什么把std::basic_string
作为函数模板的参数从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
}
我找到了一个相关的post
因为在template argument deduction中没有考虑隐式转换(从const char*
到std::basic_string<char>
),这导致模板参数推导失败Char
。
Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.
您可以明确指定模板参数,
printString<char>("hello");
或显式传递 std::basic_string
。
printString(std::basic_string("hello"));