在编译时对函数参数进行计数 [英] Counting function arguments at compile time

查看:157
本文介绍了在编译时对函数参数进行计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to count the number of arguments to a function at compile time (I'm wrapping sprintf up in some templates for compile time checks and type safety). I need to check that the number of arguments matches the number of formatting placeholders at compile time. A first pass at this is pretty simple:

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__));

但是,这对于某些类型的参数不可用.即,通过引用时.

But this breaks down for certain types of arguments. Namely, when passing a reference.

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

编译器抱怨CountArgs(__VA_ARGS__),因为xRef不是常量表达式.我不需要价值,只是需要计算它的能力.我可以将其包装在sizeof或类似的东西中,但是当我只能使用__VA_ARGS__进行操作时,这很困难.

The compiler complains about CountArgs(__VA_ARGS__) because xRef is not a constant expression. I don't need the value, just the ability to count it. I could wrap it in sizeof or something similar, but that's tough when all I have is __VA_ARGS__ to work with.

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

推荐答案

您可以将宏更改为类似的内容

You can change your macro to something like this

#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));
    ...
}

这篇关于在编译时对函数参数进行计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆