目前我正在研究一个类似于 String.Format(...)
的函数来自 C# 的函数,仅在 C++ 中。 ( String.Format(...) )
但这不是我的问题。该函数工作正常但有问题的是它需要一个 vector<string>
作为参数,如果我想使用整数作为参数,我必须编写如下代码:
// function prototype, the function body is not relevant here
string format(string str, vector<string> variables);
// ... some context
// i could use to_string() here,
// but imagine a complex type which only overrides the stream operator
int a = 20;
stringstream ss;
ss << a;
string a_str = format("a has the value '{}'", { ss.str() });
这是相当多的样板代码!
因此我需要一个函数将未知数据类型的集合转换成vector<string>
。 .
我尝试了一些这样的事情:
vector<string> vec_string(vector<void*> args) {
vector <string> result;
for (unsigned i = 0; i < args.size(); i++)
{
stringstream ss;
// I can't dereference an object without knowing to pointer type. :(
ss << *((int*)args[i]);
result.push_back(ss.str());
}
return result;
}
// ... some context
int a = 10;
cout << format("some int: '{}'", vec_string({ (void*) &a }));
这显然只适用于整数并且非常不舒服。我觉得执行此操作的唯一方法是可变参数宏,但我不知道它们是如何工作的。
here是我的 format(...)
的链接方法。
我对我的拼写感到抱歉,但我已尽力纠正它。
最佳答案
这可以通过可变参数模板相对容易地完成:
template <class T>
auto toString(T&& t) {
std::stringstream s;
s << std::forward<T>(t);
return s.str();
}
template <class... T>
auto toStringVector(T&&... args) {
std::vector<std::string> res {toString(std::forward<T>(args))...};
return res;
}
这会将每个参数转换为 std::string
通过 stringstream
然后返回 std::vector<std::string>
包含所述字符串。 ( Live example. )
然后您可以按照问题的预期直接使用它,即:
std::cout << format("some text", toStringVector(any, number, of, arguments,
of, any, type));
如果您使用的是 Boost,则可以跳过 toString
helper 赞成boost::lexical_cast
:
template <class... T>
auto toStringVector(T&&... args) {
std::vector<std::string> res { boost::lexical_cast<std::string>(std::forward<T>(args))...};
return res;
}
lexical_cast
在内置类型上很可能会更快。
关于c++ - 可变参数宏,用于从未知参数集合生成字符串 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41086436/