The default value of the parameter in the template function, depending on the type

Suppose I have this function for trimming std :: string and deciding whether to expand it, so that it removes not only spaces from beginning to end, but also any character that I pass on another line, such as spaces, characters new line and carriage return.

std::string Trim ( const std::string &In_Original,
  const std::string &In_CharsToTrim = " \n\r" );

Basically, it will remove all characters present in In_CharsToTrim from the beginning and end of In_Original.

Now I had to write this for both std :: string and std :: wstring. Since I find this absurd, I decided to use templates, and it works, but I can not pass the default value, because the version of std :: wstring should get L" \n\r"as the default value (note that there is little L there).

I tried this:

template <typename Type> Type Trim ( const Type &In_String,
  const Type &In_TrimCharacters );

together with:

template std::string Trim ( const  std::string &In_String,
  const  std::string &In_TrimCharacters = " \n\r" );
template std::wstring Trim ( const  std::wstring &In_String,
  const  std::wstring &In_TrimCharacters = L" \n\r" );

. .

, , , , :

template <typename Type> Type Trim ( const Type &In_String,
  const Type &In_TrimCharacters );
std::string Trim ( const std::string &In_String );
std::wstring Trim ( const std::wstring &In_String );

, Trim, .

, , , , ...:

? , , ...

std::string ( " \n\r" ) std::wstring ( L" \n\r" ) ...

... , , ?

+4
3

:

template <typename T> struct default_trim_chars;

template<> struct default_trim_chars<std::string> { 
    static const char* value() { return " \n\r"; }
};

template<> struct default_trim_chars<std::wstring> { 
    static const wchar_t* value() { return L" \n\r"; }
};

template <typename Type> Type Trim ( const Type &In_String,
const Type &In_TrimCharacters = default_trim_chars<Type>::value()){
    /* ... */
}

value , constexpr ++ 11.

+2

::value .

template<typename T>
struct type_sensitive_default_argument;

template<>
struct type_sensitive_default_argument<std::string>
{
     static constexpr char value[] = "\n\r";
};

template<>
struct type_sensitive_default_argument<std::wstring>
{
    static constexpr wchar_t value[] = L"\n\r";
};

:

template<class Type,
         class Default = type_sensitive_default_argument<Type>>
Type Trim(const Type& In_String,
          const Type& In_TrimCharacters = Default::value);
+3

In your case, you can rely on specifying a list of initializer characters to convert for you:

template <typename Type> Type Trim ( const Type &In_String,
  const Type &In_TrimCharacters = { ' ', '\r', '\n' } )
{
    // ...
}
+1
source

Source: https://habr.com/ru/post/1548087/


All Articles