gpt4 book ai didi

c++ - 在编译时计算函数参数

转载 作者:行者123 更新时间:2023-12-02 01:38:43 31 4
gpt4 key购买 nike

我试图在编译时计算函数的参数数量(我将 sprintf 包装在一些模板中以进行编译时检查和类型安全)。我需要检查参数的数量是否与编译时格式化占位符的数量相匹配。第一步非常简单:

template <typename... Args>
constexpr u32
CountArgs(Args&&... args)
{
return sizeof...(args);
}

constexpr u32
CountFormatSpecifiers(c8* format);

template <typename... Args>
c8*
String_FormatImpl(c8* format, Args&&... args);

#define String_Format(format, ...) \
String_FormatImpl(format, __VA_ARGS__); \
static_assert(CountFormatSpecifiers(format) == CountArgs(__VA_ARGS__));

但是对于某些类型的参数来说,这会失败。即,在传递引用时。

int x = 0;
int& xRef = x;
String_Format("%", xRef);

编译器提示 CountArgs(__VA_ARGS__) 因为 xRef 不是常量表达式。我不需要值(value),只需要计算它的能力。我可以将它包装在 sizeof 或类似的东西中,但是当我只有 __VA_ARGS__ 来使用时,这很困难。

示例:https://godbolt.org/z/Diwffy

最佳答案

您可以将宏更改为这样的内容

#define String_Format(format, ...) \
String_FormatImpl<CountFormatSpecifiers(format)>(format, __VA_ARGS__);

template <std::size_t I, typename... Args>
void String_FormatImpl(const char* format, Args&&...) {
static_assert(I == sizeof...(Args));
...
}

关于c++ - 在编译时计算函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58468574/

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