如何将数组作为参数传递,并在c ++中的参数中定义数组

时间:2013-06-24 08:49:11

标签: c++ function

我正在将c#编写的程序转换为c ++代码。我有一个c#函数声明,如:

// c# function declaration
int DerivationFunc(int id, params BasicFeature[] args); 

所以我将它转换为c ++

// c++ function declaration
int DerivationFunc(int id, BasicFeature* args, int argsNum); // argsNum denotes the size of the array

现在调用函数时遇到问题。在c#中,我可以在参数中使用数组定义调用函数:

// c# function calling
DerivationFunc(16, new BasicFeature[] {query, keyword});

那我怎么能用C ++做呢?

// c++ function calling
DerivationFunc(16, /*something like BasicFeature[] {query, keyword} but with the right syntax*/, 2);

2 个答案:

答案 0 :(得分:4)

您可以重写函数以std::initializer_list

#include <initializer_list>
#include <iostream>

struct BasicFeature {
} query, keyword;

int DerivationFunc(int id, std::initializer_list<BasicFeature> args)
{
    std::cout << args.size() << " element(s) were passed.\n";
    return id;
}

int main()
{
    DerivationFunc(42, { query, keyword });
}

答案 1 :(得分:0)

如果您不被允许使用std::initializer_list,我可以建议一些丑陋的黑客:

#include <vector>
#include <iostream>

enum BasicFeature {
    query,
    keyword
};

template<typename T>
class init_list
{
public:
    init_list &operator<<( typename T::value_type value )
    {
        m_list.push_back(value);
    }
    operator const T() const { return m_list; }
private:
    T m_list;
};

void DeriviationFunc( int id, const std::vector<BasicFeature> &args )
{
    std::cout << id << std::endl;
    std::cout << args.size() << std::endl;
    std::cout << args[0] << std::endl;
}

int main()
{
    DeriviationFunc(16, init_list<std::vector<BasicFeature> >() << query << keyword);
    return 0;
}