繁体   English   中英

编译时间:根据其中一个参数(字符串文字)调用 function

[英]Compile time: call a function based of one of the argument that is a string literals

我正在尝试创建一个 function 部分文字和部分非文字变量 arguments 返回一个 bool 并且根据结果,我必须转发所有相同的 arguments 和 order

示例 1:

int x = some_runtime_func(); // evaluated to 20
float y = some_runtime_func(); // evaluated to 10.5

MY_PRINT("{} {}", x, y); // prints 20 10.5
MY_PRINT("%d" %f", x, y); // prints 20 10.5

请注意,MY_PRINT 是一个 MACRO function,它将通过__VA_ARGS__

为此,我将解析和检查字符串并根据其内容将其转发给fmt库函数。

我设想的底层 function 是这样的(由于__VA_ARGS__崩溃而没有变量命名更改)

bool is_valid = my_formatter_checker("{} {}", x, y);
if constexpr(is_valid)
{
  fmt::print("{} {}", x, y);
}
else
{
  fmt::printf("{} {}", x, y);
}

虽然 x 和 y 不是编译时间文字,但字符串是编译时间文字,我想仅根据字符串文字来决定是否使用特定的 function。 所以对于这个例子,function 内部甚至没有使用参数 x,我只使用第一个参数

为简单起见,如果字符串不是编译时字符串,那么我将强制它在运行时对其求值。 const char* vs const char[N]我相信可以用模板类型特征来实现。

此外,fmt 允许第一个参数是特定目标,例如stdoutstderr或文件。 在这种情况下,第一个参数可以是不是字符串文字的另一种类型。

示例 2:

int x = runtime_function(); // returns 20

MY_PRINT(stderr, "{}", x); // prints 20 to stderr
MY_PRINT(stderr, "%d", x); // prints 20 to stderr

对于这种情况,我使用MY_PRINT的第二个参数,因为第二个参数是字符串文字。

主要问题是如何创建接受 constexpr 参数和非 constexpr 参数的 function my_formatter_checker ,仅解析第一个字符串参数。 无法从 function 端更改调用,这样 function 的用户就不必添加额外的宏或调用。 我希望这个 function 可以最好地使用模板元编程或 constexpr 函数来实现,因为如果参数不是字符串文字,它可以在运行时进行评估。

一种方法是使用带有隐式consteval构造函数的 class。 这就是{fmt}为编译时格式字符串检查所做的。

例如:

struct format_string {
  bool is_valid;
  const char* str;
  consteval format_string(const char* s) : str(s) {
    // Implement your compile-time logic here.
    is_valid = *s == '{';
  }
};

template <typename... T>
std::string my_print(format_string s, T&&... args) {
  if (s.is_valid)
    fmt::print(fmt::runtime(s.str), std::forward<T>(args)...);
}

为此,您需要重组代码以将所有编译时逻辑放在format_string的构造函数中,运行时逻辑在my_print function 中。

https://godbolt.org/z/7qonoPqWr

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM