【发布时间】:2022-12-29 23:31:24
【问题描述】:
我正在寻找一种使用可变大小的变量向量来格式化字符串的方法。怎么做?
我喜欢这个答案https://stackoverflow.com/a/57642429/20266935 的代码,但不幸的是,该代码不起作用,因为fmt::format 使用 constexpr 字符串。
所以我使用fmt::runtime修改了这个函数并编译,但我相信std::accumulate不能与fmt::format一起使用,因为它在一个循环中改变了字符串,一个{}被一个{}改变了,库没有像这样。
#include <fmt/core.h>
#include <numeric>
#include <iostream>
#include <vector>
std::string format_variable_size(const char* fmt, std::vector<int> args){
return std::accumulate(
std::begin(args),
std::end(args),
std::string{fmt},
[](std::string toFmt, int arg){
return fmt::format(toFmt, arg);
}
);
}
std::string runtime_format_variable_size(const char* fmt, std::vector<int> args){
return std::accumulate(
std::begin(args),
std::end(args),
std::string{fmt},
[](std::string toFmt, int arg){
return fmt::format(fmt::runtime(toFmt), arg);
}
);
}
int main()
{
std::vector<int> v = {1,2,3};
std::cout << format_variable_size("[{}, {}, {}]\n", v);
std::cout << runtime_format_variable_size("[{}, {}, {}]\n", v);
return 0;
}
https://godbolt.org/z/337cGEh6d
有什么办法可以做到吗?
【问题讨论】:
-
这似乎不可行,因为在编译时需要知道向量的大小。