2

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

// 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);
4

2 回答 2

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 });
}
于 2013-06-24T08:57:27.937 回答
0

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

#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;
}
于 2013-06-24T09:27:52.453 回答