c++ - C++ 的混合类型、可变长度参数列表(varargin、*args、...)

标签 c++ matlab

我正在构建一个最初用 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/

相关文章:

c++ - SFINAE 启用/禁用功能和模板别名

c++ - 包含 <stdlib> 时出现 fatal error

将Matlab/C函数转换为无源代码版本

python - 如何在 Python 中制作 3D 图?

matlab - Matlab repelem 的 Eigen 等价物是什么?

c++ - 是否可以为类成员模板特化(和类模板成员特化)设置不同的访问修饰符?

c++ - 从cpp中的mysql blob解析BMP文件

matlab - Matlab的默认显示功能等效于什么,它输出到文件而不是stdout?

c# - 如何从 C# 中的 com 对象返回数组(double[])?

java - 我们可以在 MATLAB 中应用密码学技术吗?