同类型多函数参数能否省略重复类型声明?如何简化给定函数写法?
多同类型函数参数的简化写法
针对你给出的C风格函数示例,不同编程语言有不同的简化方案,这里重点讲C和C++的处理方式:
C语言:
C标准语法里没有直接批量声明同类型参数的写法,必须为每个参数显式指定类型。如果非要简化,可以用宏来批量生成参数声明,但这种写法会降低代码可读性,团队协作时不推荐使用。示例如下:#define DOUBLE_ARGS(x1, y1, x2, y2, x3, y3, x4, y4) double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4 double function(DOUBLE_ARGS(x1, y1, x2, y2, x3, y3, x4, y4)) { // 函数体 }C++语言:
有几种更优雅的简化方式,适配不同的C++版本:- 初始化列表(C++11+):
把所有同类型参数打包成std::initializer_list,调用时用大括号传递参数,函数内部通过迭代器访问各个值:#include <initializer_list> double function(std::initializer_list<double> coords) { // 比如获取第一个参数:*coords.begin(),第二个:*(coords.begin()+1),以此类推 // 函数体 } // 调用示例:function({1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}); - 结构化绑定(C++17+):
如果参数是成对的坐标,可以把它们封装成结构体,或者直接用tuple打包,在函数内部用结构化绑定快速提取各个变量:#include <tuple> // 用结构体的方式 struct Point { double x; double y; }; double function(Point p1, Point p2, Point p3, Point p4) { auto [x1, y1] = p1; auto [x2, y2] = p2; auto [x3, y3] = p3; auto [x4, y4] = p4; // 函数体 } // 用tuple的方式 double function(std::tuple<double, double, double, double, double, double, double, double> coords) { auto [x1, y1, x2, y2, x3, y3, x4, y4] = coords; // 函数体 } - 变参模板(C++11+):
如果参数数量不固定,且要求所有参数都是double类型,可以用变参模板配合类型检查来实现:#include <type_traits> template<typename... Args, typename = std::enable_if_t<(std::is_same_v<Args, double> && ...)>> double function(Args... args) { // 可以用sizeof...(args)获取参数总数,再处理各个参数 // 函数体 }
- 初始化列表(C++11+):
另外,如果是Python、JavaScript这类动态类型语言,本身就不需要声明参数类型,自然不存在重复写类型的问题,但你的示例是C风格函数,所以以上方案更贴合你的需求。
内容的提问来源于stack exchange,提问作者cryon234
相关产品推荐
相关产品推荐

