1
template <typename ty_char, /* template <typename> typename ... tys_str
↑ I cant define the parameter pack
to express that paramater pack is constrainted to basic_string classes with a template argument */ >
void
concat_strings( basic_string<ty_char> & _buffer,
                tys_str<ty_char> const & ... _string )
{
    static_assert( is_same<basic_string<ty_char>::size_type, size_t>::value );
    size_t l_min_size = 0;

    for( auto const & l_string : {_string...} )
    {
        l_min_size += l_string.size( );
    }

    _buffer.reserve( l_min_size );

    for( auto const & l_string : {_string...} )
    {
        _buffer += _string;
    }
}

I have been trying to implement the function which receives a reference of the buffer and concatenates other constant strings. I want the function receives the arguments without any array allocation. However, I feel the function gets more messy and totally wrong. Is it a proper way to implement the function?

Boma Kim
  • 33
  • 5

1 Answers1

3

If you want to make sure only to allow strings then simply define them as such:

template <typename ty_char, typename ... tys_str>
void concat_strings
(
    std::basic_string<ty_char>& buffer,
    std::basic_string<tys_str> const& ... strings
)

Then instead of looping via arrays fold expressions are your friend:

buffer.reserve( ( strings.length() + ... ) );
//              ^                        ^
( (buffer += strings), ... );

Requires C++17 for the fold expressions; pre-C++17 code would rely on recursing into the variadic parameters to avoid the intermediate arrays (that might get optimised out anyway).

You don't need the static_assert, by the way, the standard guarantees size_type being size_t already.

Instead you might want to make sure all the strings are of the same type, again with a fold expression:

static_assert( (std::is_same_v<ty_char, tys_str> && ...) );
Aconcagua
  • 24,880
  • 4
  • 34
  • 59
  • It is weird that clang++ in visual studio 2022 community, Windows 10, shows me errors: "the fold expressions does not refer to a parameter pack" but there is no problem to build a executable program with the function 'concat_strings'. Even in the command prompt, clang++.exe emits no error. I think it is a bug of IDE. – Boma Kim Mar 30 '23 at 09:51
  • 1
    Not experienced with MSVC too much, I avoid it wherever possible... Its advantage is its easy setup, admitted – other IDE like eclipse or code::blocks require quite some effort to get them running properly (needing to include external compiler), but once this task is done they are superior (again admitted, MS did quite some effort to reduce the distance, but still they remain behind). – Aconcagua Mar 30 '23 at 09:59
  • Move on to C++20:`template ... tys_str>` instead of `static_assert`. – Red.Wave Mar 30 '23 at 11:21