0

So I want to pass an array of std::strings to a function. The number of std::strings in the array is predefined via preproc. directives. The whole thing should look like this:

#define ARRAYSIZE 3
void foo(std::string[ARRAYSIZE]);
void foo(std::string instrings[ARRAYSIZE])
{
...
}

Question: Can I call on the function without having to save the std::string array first to a variable, and then calling with that? So basically I want to call it with one line, like:

void main()
{
...
foo( std::string x[ARRAYSIZE] = {"abc","def","ghi"}  );
...
}

Problem is that I can't figure out the correct syntax of the function call (I'm not even sure there is one), visual studio's intellisense keeps shooting my ideas down.

8
  • 7
    Using std::array and std::vector is good for the soul. Commented Jul 7, 2014 at 1:06
  • 1
    #define for constants is totally unnecessary. Use const or constexpr instead. Commented Jul 7, 2014 at 1:09
  • @chris I'd say it depends on the scope. If I am to use the same array length on multiple unrelated functions, and the length must be exactly the same I'd use a define. But then again it's not exactly best practice, and this comes from a C perspective... at the end of the day, it doesn't really matter. Commented Jul 7, 2014 at 1:12
  • @rath, You can use a global constant if you really need to. At least it's actually an object that obeys scoping rules and not just text being replaced. Commented Jul 7, 2014 at 1:14
  • @chris +1, the text-replace argument makes sense. Commented Jul 7, 2014 at 1:15

2 Answers 2

3

If you would like to switch to std::vector that can be constructed on the fly as you have mentioned in the comment to the question, this should work (works with gcc):

void foo(const std::vector<std::string> &stringVec)
{
}

int main()
{
    foo( std::vector<std::string>({"abc","def","ghi"}));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works! :) I had to rewrite foo so it expects a vector, which means the compiler doesn't check the array's size anymore, it accepts any vector of strings, but I can just check it myself and give some horrible error message if the size is not ARRAYSIZE
1

One way to pass multiple values like this {x0,x1,x2,...} would be to use std::initializer_list which was introduced in c++11. Although this way it is not possible to force a constant number of values.

void foo(const std::initializer_list<std::string>& input) {

}

int main() {
    foo({"abc","def","ghi"});
}

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.