【发布时间】:2021-09-18 00:40:24
【问题描述】:
我正在使用这样的函数将数据导出到 xml 文件中(注意:愚蠢的示例):
void write_xml_file(const std::string& path)
{
using namespace std::string_view_literals; // Use "..."sv
FileWrite f(path);
f<< "<root>\n"sv
<< "\t<nested1>\n"sv
<< "\t\t<nested2>\n"sv
<< "\t\t\t<nested3>\n"sv
<< "\t\t\t\t<nested4>\n"sv;
//...
}
那些<< 采用std::string_view 参数的地方:
FileWrite& FileWrite::operator<<(const std::string_view s) const noexcept
{
fwrite(s.data(), sizeof(char), s.length(), /* FILE* */ f);
return *this;
}
如有必要,我可以使用std::string、std::array、...添加重载
现在,我真的很想这样写:
// Create a compile-time "\t\t\t..."sv
consteval std::string_view indent(const std::size_t n) { /* meh? */ }
void write_xml_file(const std::string& path)
{
using namespace std::string_view_literals; // Use "..."sv
FileWrite f(path);
f<< "<root>\n"sv
<< indent(1) << "<nested1>\n"sv
<< indent(2) << "<nested2>\n"sv
<< indent(3) << "<nested3>\n"sv
<< indent(4) << "<nested4>\n"sv;
//...
}
有没有人可以给我一个关于如何实现indent()的提示?
我不确定返回一个指向在编译时分配的静态常量缓冲区的std::string_view 的想法是否最合适,我愿意接受其他建议。
【问题讨论】:
-
indent<N>()更适合编译时计算。 -
consteval是 C++20,您已将问题标记为 C++17。做出决定并更新。 -
当然可以,前提是您在编译时使
N发生,但indent<N>有 返回string_view对象吗? IMO 使用indent<N>(ostream&)实际上缩进流的函数可能更有意义。这也更容易编写,因为它只是递归地附加一个'\t'并调用indent<N-1>直到它到达0 -
@PaulMcKenzie: 但是
std::string无论如何不能从constexpr方法返回。 -
@PaulMcKenzie
std::string的构造函数只有constexpr,因此它可以在核心常量子表达式中使用,但您不能生成 constexprstring并将其返回给非-constexpr 上下文 AFAIK。就像constexpr auto s = std::string{2, '\t'};is illegal in C++20 在 constexpr 上下文之外,operator<<forstd::ostream&不符合条件。
标签: c++ c++20 string-literals compile-time string-view