c++ - 使用 << 运算符构造 std::string

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

如果我们想构造一个复杂的字符串,可以这样说: “我有 10 个 friend 和 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 中有更简单的方法?

最佳答案

#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

关于c++ - 使用 << 运算符构造 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35012814/

相关文章:

c++ - 为什么 wifstream.read 函数不读取数据到变量?

c++ - 在虚析构函数中调用其他虚方法是否安全?

c++ - 使用 CATCH C++ 单元测试框架测试两个 std::vectors 是否相等

影响 "HAS-A Parent"的 C++ 状态机

c++ - 在嵌套类型中保留 volatile

c++ - 存储在 vector 中的图像都是相同的

Java:字符串模式:如何为所有具有特殊字符的字母字符指定正则表达式

java - 不使用数组计算字符串中的唯一单词

r - 在 data.frame 中查找字符串

java - 如何将加密数据从 C++ 传输到 Java