我正在构建一个最初用 MATLAB 编写的项目的 C++ 克隆。我想“翻译”尽可能接近原始代码的代码(考虑到像 MATLAB 这样的动态类型语言和像 C++ 这样的静态类型语言之间不可避免的差异)。
我的问题是关于可变长度参数列表作为函数参数,它可以包含混合类型的参数。
MATLAB 将 varargin
作为函数参数:
varargin Variable length input argument list.
Allows any number of arguments to a function. The variable
varargin is a cell array containing the optional arguments to the
function. varargin must be declared as the last input argument
and collects all the inputs from that point onwards. In the
declaration, varargin must be lowercase (i.e., varargin).
在 Python 中,*args
和 **kwargs
可以很轻松地处理这个问题。
在 C++ 中,我有多接近这种灵 active ?有没有我应该使用的标准参数列表类?
最佳答案
如果您只想传递少数(简单)类型的参数,std::vector<>
作为参数传递非常简单易行。
通常你会创建这样的结构:
struct Option {
union {
int Int;
float Float;
} Number;
string String;
};
您可以选择添加 Type
Option 结构的字段,用于 switch
声明。
在 C++11 中,甚至应该可以在 union 中使用 std::string,但我对此不是 100% 确定。
<cstdarg>
是另一种解决方案,如果您使用的是 C 函数(例如 vsprintf
),这很好.
关于c++ - C++ 的混合类型、可变长度参数列表(varargin、*args、...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10261185/