c++是否支持函数的参数数量可变?

Does C++ support variable numbers of parameters to functions?

本文关键字:数数 参数 是否 支持 函数 c++      更新时间:2023-10-16

printf ?

但是我记得c++对函数名和参数类型进行了名称混淆,

这可以推断c++不支持变长形参…

我只是想确定一下,是这样的吗?

讨论应排除extern "C"中包含的内容

是。c++从C中继承了这一点。

void f(...);

这个函数可以接受任意数量的任意类型的实参。但这不是很c++的风格。程序员通常会避免这样的编码。

然而,有一个例外:在模板编程中,SFINAE大量使用了这一点。例如,请看下面这段(摘自这里):

template <typename T>
struct has_typedef_type {
    // Variables "yes" and "no" are guaranteed to have different sizes,
    // specifically sizeof(yes) == 1 and sizeof(no) == 2.
    typedef char yes[1];
    typedef char no[2];
    template <typename C>
    static yes& test(typename C::type*);
    template <typename>
    static no& test(...);
    // If the "sizeof" the result of calling test<T>(0) 
    // would be equal to the sizeof(yes), the first overload worked 
    // and T has a nested type named type.
    static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};

这使用了一个可变函数test(...)

是的,c++支持C中的省略号,但我强烈建议不要使用它们,因为它们绝不是类型安全的。

如果你有一个很好的c++ 11编译器,支持可变模板,那么你应该使用它。如果您还没有,请查看boost::format如何解决这些问题。