连接一个字符串系列

Ins*_*oop 5 c++ string string-concatenation

我想编写一个函数,它连接场景后面std::string只有一个malloc的任何序列.因此,需要首先计算字符串的总长度.该函数需要以这种方式使用:

std::string s0 = ...;
std::string s1 = ...;
std::string s2 = ...;

std::string s = join(s0, s1, s2);
Run Code Online (Sandbox Code Playgroud)

一个更好的join将使用的混合std::stringstd::string_view.如果我们可以添加字符串文字会更好.你会如何在C++ 11中编写这样的函数(它需要用gcc 4.8.5和编译Visual Studio 2015)?

Ben*_*hon 2

这是一个可能的实现:

template<typename... Args>
std::string join(const Args&... args)
{
    size_t size = 0;
    for( const std::string& s : { args... } )
        size += s.size();

    std::string result;
    result.reserve(size);
    for( const std::string& s : { args... } )
        result += s;
    return result;
}
Run Code Online (Sandbox Code Playgroud)

演示: https: //wandbox.org/permlink/qwG0LMewsHwVuGXN