如果我们想构造一个复杂的字符串,可以这样说: “我有 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);
}
关于c++ - 使用 << 运算符构造 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35012814/