没有命名参数的可变参数函数 [英] Variadic function without named argument

查看:31
本文介绍了没有命名参数的可变参数函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,GCC 和 MSVC 都对以下代码感到满意:

I noticed, that both GCC and MSVC are happy with the following code:

#include <iostream>
void foo(...);

int main()
{
    foo();
}

void foo(...)
{
    std::cout << "foo\n";
}

更具体地说,代码在 GCC 6.2.0 和 Visual Studio 2015 下运行.

More specifically, code was run under GCC 6.2.0 and Visual Studio 2015.

我知道 C 需要在省略号前至少有一个 named 参数,它允许使用专门的 va_startva_args 处理任意数量的参数> 和 va_end 宏来自 (此处为 )标头.否则,它甚至不会编译.

I know that C requires at least one named parameter preceding the ellipsis, which allows to handle any number of arguments using specialized va_start, va_args, and va_end macros from <stdarg.h> (here <cstdarg>) header. Otherwise, it won't even compile.

C++ 是否对纯省略号"形式有一些特殊处理,或者它不适合获取参数,即它是允许的,但完全不切实际?

Does C++ have some special treatment for "pure ellipsis" form or is it not suitable for fetching the arguments, i.e. it's allowed, but completely impractical?

推荐答案

C++ Variadiac 参数是在这里解释.C++ 支持此语法,但无法访问参数:

C++ Variadiac arguments are explained here. This syntax is supported in C++, but the arguments are not accessible:

在C编程语言中,省略号参数前必须至少出现一个命名参数,所以printz(...);是无效的.

In the C programming language, at least one named parameter must appear before the ellipsis parameter, so printz(...); is not valid.

在 C++ 中,即使传递给这样的参数,也允许这种形式函数不可访问,通常用作后备SFINAE 中的过载,利用省略号的最低优先级重载决议中的转换.可变参数的这种语法是在 1987 年 C++ 中引入的,省略号前没有逗号.什么时候C89 采用了 C++ 的函数原型,将语法替换为一个需要逗号.为了兼容性,C++98 接受两者C++ 风格的 f(int n...) 和 C 风格的 f(int n, ...)

In C++, this form is allowed even though the arguments passed to such function are not accessible, and is commonly used as the fallback overload in SFINAE, exploiting the lowest priority of the ellipsis conversion in overload resolution. This syntax for variadic arguments was introduced in 1987 C++ without the comma before the ellipsis. When C89 adopted function prototypes from C++, it replaced the syntax with one requiring the comma. For compatibility, C++98 accepts both C++-style f(int n...) and C-style f(int n, ...)

这篇关于没有命名参数的可变参数函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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