C++ c+中类似printf的实用程序+;没有格式说明符?
我正在尝试编写一个函数,可以将其参数转换为字符串。但是,我发现很难打开参数包 以下是我编写的代码:C++ c+中类似printf的实用程序+;没有格式说明符?,c++,variadic-templates,variadic-functions,C++,Variadic Templates,Variadic Functions,我正在尝试编写一个函数,可以将其参数转换为字符串。但是,我发现很难打开参数包 以下是我编写的代码: #include <iostream> #include <sstream> template <typename... T> std::string StringFormatter(T... values) { std::ostringstream out; for (auto&& x : { values... }) {
#include <iostream>
#include <sstream>
template <typename... T>
std::string StringFormatter(T... values)
{
std::ostringstream out;
for (auto&& x : { values... }) {
out << x;
}
return out.str();
}
int main()
{
auto&& i = StringFormatter("One ", "two"); //Success
auto&& j = StringFormatter("one ", 1, "two", 2.0); //Fails
std::cout << i;
}
#包括
#包括
样板
字符串字符串格式化程序(T…值)
{
std::ostringstream out;
对于(自动(&x:{values…}){
out您可以使用C++17实现这一点:
模板
字符串字符串格式化程序(T…值)
{
std::ostringstream out;
(out现在有更好的方法(使用折叠表达式),但是如果您想使用递归方法,它可以如下所示:
#include <sstream>
#include <string>
#include <iostream>
template <class T>
std::string stringify(T const &t) {
std::stringstream b;
b << t;
return b.str();
}
template<typename T, typename... Args>
std::string stringify(T arg, const Args&... args) {
return stringify(arg) + stringify(args...);
}
int main() {
std::string three{" three"};
std::cout << stringify("one: ", 1, " two: ", 2, three, "\n");
return 0;
}
#包括
#包括
#包括
样板
字符串字符串化(T常量&T){
std::stringstream b;
简而言之:
如果没有C++17编译器,可以使用int数组技巧:
template <typename... T>
std::string StringFormatter(T... values) {
std::ostringstream out;
int arr[] = { 0, (out << values, void(), 0)... };
return out.str();
}
假设,
运算符没有重载,则该语句将被计算为其他对象
。但这并不意味着忽略某个对象
。它的值只是被丢弃,取而代之的是其他对象
。我们将该属性用于我们的小技巧
int x = 0;
int a[] = { 0, (++x, 0) }; // a is {0, 0}, x is 1
现在,由于您可以重载运算符,
,我们只需添加一条附加语句来避免这种假设的重载:
(something, void(), 0)
由于运算符,
是一个二进制运算符,它的重载版本不能只有一个参数。通过向void
添加一个求值语句,我们可以防止拾取任何假设的重载,因此可以确定我们最终得到的是0
最后一步是将其与参数pack相结合,并对结果语句执行pack扩展:
(out << values, void(), 0)...
(发布你的递归代码。你可以使用std::stringstream,请参阅@user202729,它没有编译。我试图从每个函数调用返回std::tuple。我发现没有std方法也可以遍历tuple的元素。我们必须使用boost库来完成这项工作。你使用的是c++17吗?顺便说一句,你不应该在p中包含'thank'osts。请参阅此meta post:@user202729同意。这将占用线性内存…不管怎样。计算顺序有保证吗?@user202729计算顺序有保证。编译器应该能够优化结果二进制中的数组。@Rerito它正在工作。但我无法理解它的机制。您能解释一下吗更详细地说。@AmitBhaira只需尝试手动扩展包,例如,2个参数。
int x = 0;
int a[] = { 0, (++x, 0) }; // a is {0, 0}, x is 1
(something, void(), 0)
(out << values, void(), 0)...