c++templates

std::basic_string_view with one template argument


In MSVC's Standard Library and in libc++ std::basic_string_view is declared like this:

template <class _Char, class _Traits>
class basic_string_view {
    // ...
};

Note, that there is no default template argument for _Traits, unlike in libstdc++, which has one. Still, I can instantiate it with only one template argument. This compiles:

#include <string_view>

using MyStringView = std::basic_string_view<char>;

Why don't I get too few template arguments error?


Solution

  • For MSVC, search the code for the first occurrence of "basic_string_view" in the header to which you linked. Line 1190 declares the default for the second template parameter.

    template <class _CharT, class _Traits = char_traits<_CharT> >
    class basic_string_view;
    

    For libc++, the forward declaration is hidden in one of the header's headers. Not hard to find, though. After the search for the text "basic_string_view" fails to yield an answer, searching for "string_view" leads to the aptly-named __fwd/string_view.h, line 22.

    template <class _CharT, class _Traits = char_traits<_CharT> >
    class basic_string_view;
    

    Once the forward declaration establishes the default parameter, it would be an error to repeat it. Besides, it's better to avoid repetitive code when you can.