0

我正在构建最初用 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++ 中,我离这种灵活性有多近?我应该使用任何标准的参数列表类吗?

4

1 回答 1

1

如果您只想传递几个(简单)类型的参数,std::vector<>则作为参数传递非常简单明了。

通常你会创建这样的结构:

struct Option {
    union {
        int Int;
        float Float;
    } Number;
    string String;
};

Type或者,您可以向 Option 结构添加一个字段,以在switch语句中使用。

在 C++11 中,甚至应该可以在联合中使用 std::string,但我对此不是 100% 确定的。

<cstdarg>是另一种解决方案,如果您使用 C 函数(例如vsprintf.

于 2012-04-21T17:20:40.797 回答