c++是否支持函数的参数数量可变?
Does C++ support variable numbers of parameters to functions?
像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如何解决这些问题。
相关文章:
- C++函数模板需要 &for 数组参数
- C++ 数组参数不起作用
- 使用数组参数进行函数专用化
- 为什么我的数组参数的方法无法正常工作?(C )
- SWIG - Java 代理类数组参数
- 在 gcc 中使用数组参数编译外部"c"代码
- 从 VB6 调用的 C++ DLL 函数中的输出数组参数
- 基于模板参数的模板类力数的参数
- 如何根据数组参数项类型重载 IDL 中的函数
- 引用谷歌测试/模拟框架中的数组参数
- 比特菲尔德,标志数为参数
- C++将数组参数传递给函数
- 字符星形数组参数未正确终止
- 如何将德尔菲的"字符串数组"参数翻译成C++?
- 为什么 gcc 无法推断数组参数的模板化大小?(C++11)
- 使用 const char 数组参数分析 constexpr 显示运行时执行
- C++指针数组参数
- 固定大小的多维数组参数
- 为什么数组参数被视为常量数组
- 如何在pgsql中格式化数组参数