简体   繁体   中英

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

I am converting ac# written program into c++ code. I have ac# 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);

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 });
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM