使用<<构造std :: string操作者

时间:2016-01-26 11:29:53

标签: c++ string c++11 std c++14

如果我们想构建一个复杂的字符串,请这样说: “我有10个朋友和20个关系”(其中10和20是某些变量的值)我们可以这样做:

std::ostringstream os;
os << "I have " << num_of_friends << " friends and " << num_of_relations << " relations";

std::string s = os.str();

但它有点太长了。如果代码中的不同方法需要多次构造复合字符串,则必须始终在其他地方定义std :: ostringstream的实例。

在一行中是否有更短的方法?

我创建了一些额外的代码,以便能够做到这一点:

struct OstringstreamWrapper
{
     std::ostringstream os;
};

std::string ostream2string(std::basic_ostream<char> &b)
{
     std::ostringstream os;
     os << b;
     return os.str();
}

#define CreateString(x) ostream2string(OstringstreamWrapper().os << x)

// Usage:
void foo(int num_of_friends, int num_of_relations)
{
     const std::string s = CreateString("I have " << num_of_friends << " and " << num_of_relations << " relations");
}

但也许在C ++ 11或Boost中有更简单的方法?

2 个答案:

答案 0 :(得分:3)

#include <string>
#include <iostream>
#include <sstream>

template<typename T, typename... Ts>
std::string CreateString(T const& t, Ts const&... ts)
{
    using expand = char[];

    std::ostringstream oss;
    oss << std::boolalpha << t;
    (void)expand{'\0', (oss << ts, '\0')...};
    return oss.str();
}

void foo(int num_of_friends, int num_of_relations)
{
    std::string const s =
        CreateString("I have ", num_of_friends, " and ", num_of_relations, " relations");
    std::cout << s << std::endl;
}

int main()
{
    foo(10, 20);
}

Online Demo

答案 1 :(得分:1)

您可以使用Boost.Format

#include <iostream>
#include <boost/format.hpp>

using boost::format;

int main()
{
    std::cout << boost::format("I have %1% friends and %2% relations")
        % num_of_friends % num_of_relations; 
}