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;
}
}
我一直在尝试实现接收缓冲区引用并连接其他常量字符串的函数。我希望函数接收参数,而不需要任何数组分配。然而,我觉得这个函数变得更加混乱和完全错误。这是一个适当的方式来实现的功能?
如果您想确保只允许字符串,那么只需这样定义它们:
template <typename ty_char, typename ... tys_str>
void concat_strings
(
std::basic_string<ty_char>& buffer,
std::basic_string<tys_str> const& ... strings
)
那么,除了通过数组循环之外,折叠表达式是你的朋友:
buffer.reserve( ( strings.length() + ... ) );
// ^ ^
( (buffer += strings), ... );
需要c++ 17来使用fold表达式;c++ 17之前的代码将依赖递归到可变参数来避免中间数组(无论如何都可能被优化掉)。
你不需要static_assert
,顺便说一下,标准已经保证size_type
是size_t
了。
相反,您可能希望确保所有字符串都是同一类型,再次使用折叠表达式:
static_assert( (std::is_same_v<ty_char, tys_str> && ...) );