2

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);
3
  • Is your C++ array fixed size, or dynamically allocated? Commented Jun 24, 2013 at 8:54
  • Use std::vectoror std::array. en.cppreference.com/w/cpp/container/array Commented Jun 24, 2013 at 8:56
  • @juanchopanza, let's assume it's fixed size. Dynamically allocation is also considered. Commented Jun 24, 2013 at 9:00

2 Answers 2

4

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 });
}
Sign up to request clarification or add additional context in comments.

3 Comments

This is a fancy way, but I am not using C++0x which not support std::initializer_list.
Then I believe you're out of luck as far as writing braced-init-list in function call goes. Check juanchopanza's answer then.
@zwx: The name of C++0X has been changed to C++11 about 3 years ago. Also, All major compilers (GCC, VC++, ...) already have implemented C++11 features. C++11 is the new C++ standard and it replaced C++03.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.