我编写了以下函数模板:
#include <string>
#include <string_view>
template <typename CharT,
typename Traits = std::char_traits<CharT>>
int fun(std::basic_string_view<CharT, Traits> str1)
{
return 0;
}
这个想法是能够使用任何类型的
string_view
调用该函数。一般来说,这似乎有效。
但是,如果我尝试使用
string
调用该函数,则会出现编译错误:
int main()
{
std::string s1("String 1");
fun(s1);
}
结果
/usr/bin/g++ -fdiagnostics-color=always -g /home/jeff/Projects/xxx/jkb.cpp -o /home/jeff/Projects/xxx/jkb -std=c++17 -I../include
/home/jeff/Projects/xxx/jkb.cpp: In function ‘int main()’:
/home/jeff/Projects/xxx/jkb.cpp:20:8: error: no matching function for call to ‘fun(std::string&)’
20 | fun(s1);
| ~~~^~~~
/home/jeff/Projects/xxx/jkb.cpp:6:5: note: candidate: ‘template<class CharT, class Traits> int fun(std::basic_string_view<_CharT, _Traits>)’
6 | int fun(std::basic_string_view<CharT, Traits> str1)
| ^~~
/home/jeff/Projects/xxx/jkb.cpp:6:5: note: template argument deduction/substitution failed:
/home/jeff/Projects/xxx/jkb.cpp:20:8: note: ‘std::__cxx11::basic_string<char>’ is not derived from ‘std::basic_string_view<_CharT, _Traits>’
20 | fun(s1);
| ~~~^~~~
如果我明确地将
s1
转换为 string_view
fun(static_cast<std::string_view>(s1));
有效。
为什么尝试隐式转换
string
无法匹配任何可能的 string_view
参数到 fun
失败?为什么有关 string
的消息不是源自 string_view
?
谢谢。
根据cppreference,
类型推导不考虑隐式转换(除了上面列出的类型调整之外):这是重载决策的工作,稍后发生
我还要添加一个问题:您使用了多少种不同的字符串类型?我必须承认我还没有尝试过,但是普通的
std::string_view
不仅需要 std::string
没有任何麻烦,而且还需要字符串文字——我怀疑这也可能不适用于您的解决方案。