构造std :: string使用<<运算符 [英] Constructing std::string using << operator
本文介绍了构造std :: string使用<<运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我们要构造一个复杂的字符串,像这样:
我有10个朋友和20个关系(其中10和20是一些变量的值)它像这样:
If we want to construct a complex string, say like this: "I have 10 friends and 20 relations" (where 10 and 20 are values of some variables) we can do it like this:
std::ostringstream os;
os << "I have " << num_of_friends << " friends and " << num_of_relations << " relations";
std::string s = os.str();
但它有点太长了。如果在你的代码中的不同方法中你需要多次构造复合字符串,你必须总是在其他地方定义一个std :: ostringstream的实例。
But it is a bit too long. If in different methods in your code you need to construct compound strings many times you will have to always define an instance of std::ostringstream elsewhere.
我创建了一些额外的代码来实现这一点:
I created some extra code for being able to do this:
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中有更简单的方法?
But maybe there is simpler way in C++ 11 or in 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);
}
这篇关于构造std :: string使用<<运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文