gpt4 book ai didi

c++ - 使用 C 格式字符串构建 C++ 字符串的最佳方法是什么?

转载 作者:行者123 更新时间:2023-11-30 02:42:31 24 4
gpt4 key购买 nike

我想在我公司的代码中添加一个 std::string fmtString(char const * fmt, ...);函数,它允许我以 printf 方式从 C 对象构建 C++ 字符串。我真的很喜欢 C 格式字符串的可读性,并且想把它带过来而不是使用 operator<< 的 C++ 风格。或 operator+ .

  1. 这是一个糟糕/低效的想法吗?
  2. 这是否已经存在,或者在没有自定义方法的情况下是否已经很容易以 C 风格构建 C++ 字符串?
  3. 实现这种方法的最佳方式是什么?它必须是线程安全的。

编辑:这需要在没有 C++11 的情况下工作,但我仍然对 C++11 问题的解决方案感兴趣!

最佳答案

template<class...Args>
std::string fmt( string_view, Args&&... )

是此类函数的 C++11 签名。这允许运行时类型安全和受控故障。

不要使用 C 风格的 VA-args,因为这使得任何类型的合理故障都不可能发生(类型检查、arg 计数检查等)。

解析 string_view 将在运行时花费时间,但除此之外,这里没有根本的低效率。将字符串转换为已解析格式化程序的 constexpr 解析器可能是个好主意,可能是字符串文字。

boost 有许多 C 风格的 C++ 格式化程序。

您需要遍历格式字符串,寻找格式命令。在进行时转储非格式文本。在每个格式命令中,打开它并将一个或多个 Args 消费到您期望的类型的错误生成消费者中。

一个 %d 消费者的例子是:

template<class T> struct simple_printer;

template<> struct simple_printer {
void operator()( std::string& s, int x ) const {
// TODOL print x to s
}
};
template<class X, class... Ts>
std::false_type
simple_print(std::false_type, Ts&&...) { return {}; }

template<class X, class...Args>
std::true_type
simple_print(std::true_type, std::string& out, Args&&... in ) {
simple_printer<X>{}( out, std::forward<T>(t) );
}

然后在解析代码中,当您遇到 %d 时,您会:

if (fmt_code == "%d") {
auto worked = simple_print( std::is_convertible<Arg0, int>{}, out, std::forward<Arg0>(arg0) );
if (!worked) {
// report error then
return;
}
}

在解析每个格式命令后,您使用较少的参数和格式字符串的尾端递归打印函数。

处理更复杂的格式(如 %.*f)自然更棘手。如果您请求以某种方式在 Args 中对“格式化包”参数进行分组,这可能会有所帮助。

关于c++ - 使用 C 格式字符串构建 C++ 字符串的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26997020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com