Search code examples
c++templatesc++20string-view

How to let a template function accept anything you can construct some basic_string_view out


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.


Solution

  • It's also possible to do this using just C++20 by checking whether the argument passed to the function is a range. The range can then be converted to a basic_string_view using its constructor overload that takes iterators.

    I've also added an overload that can deal with char pointers since those aren't ranges.

    #include <string_view>
    #include <string>
    #include <type_traits>
    #include <ranges>
    
    
    template <typename CharT, typename Traits>
    void func(std::basic_string_view<CharT, Traits> value) {
        // ...
    }
    
    template<typename S> requires std::ranges::contiguous_range<S>
    void func(const S& s) {
        func(std::basic_string_view{std::ranges::begin(s), std::ranges::end(s)});
    }
    
    template<typename S> requires (!std::ranges::range<S> && requires (S s) { std::basic_string_view<std::remove_cvref_t<decltype(s[0])>>(s); })
    void func(const S& s) {
        func(std::basic_string_view<std::remove_cvref_t<decltype(s[0])>>(s));
    }