I'm trying to write a simple template function which accepts all possible basic_string_view but i always get the compiler error "no matching overloaded function found".
I don't know the reason; explicitly converting to string_view by the caller works but i'd like to avoid that; or is intentionally made hard?
Are there deduction guidelines which prevent this?
And is there a easy way to implement this as a template?
Here (and on godbolt) is what i tried:
#include <string_view>
#include <string>
template <typename CharT, typename Traits> void func(std::basic_string_view<CharT, Traits> value)
//template <typename CharT> void func(std::basic_string_view<CharT> value)
//void func(std::string_view value)
{}
int main() {
std::string s;
std::string_view sv(s);
char const cs[] = "";
std::string_view csv(cs);
std::wstring ws;
std::wstring_view wsv(ws);
wchar_t const wcs[] = L"";
std::wstring_view wcsv(wcs);
func(s);
func(sv);
func(cs);
func(csv);
func(ws);
func(wsv);
func(wcs);
func(wcsv);
}
Here are the errors msvc, clang and gcc show:
error C2672: 'func': no matching overloaded function foundx64 msvc v19.latest #3
error C2783: 'void func(T)': could not deduce template argument for '<unnamed-symbol>'x64 msvc v19.latest #3
error: no matching function for call to 'func'x86-64 clang (trunk) #1
error: no matching function for call to 'func(std::string&)'x86-64 gcc (trunk) #2
EDIT:
Demo of a blend of Yakks c++20 answer with the addition of Jonathans raw character pointer support.
basic_string_view has a range version of CTAD in C++23, so in C++23, you can use the requires clause to constrain basic_string_view{s} to be well-formed, and deduce its type by borrowing the CTAD of basic_string_view in the function body
#include <string_view>
template<typename StrLike>
requires requires (const StrLike& s)
{ std::basic_string_view{s}; }
void func(const StrLike& s) {
auto sv = std::basic_string_view{s};
// use sv
}
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With