stackunderflow
stackunderflow

Reputation: 907

how pass an array as parameter, and the array is defined in the parameters in c++

I am converting a c# written program into c++ code. I have a c# function declaration like:

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

So I convert it to c++

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

Now I have problems when calling the functions. In c#, I can call the function with the array definition in the parameters:

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

So how can I do this in C++?

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

Upvotes: 2

Views: 118

Answers (2)

Kane
Kane

Reputation: 6250

If you are not allowed to use std::initializer_list, I could suggest a little ugly 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;
}

Upvotes: 0

jrok
jrok

Reputation: 55395

You could rewrite the function to take 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 });
}

Upvotes: 4

Related Questions