Reputation: 5606
I have a function with signature like this:
void foo(const std::vector<std::string>& args)
{
...
}
I want convert vector args
to const char **
(just like argv
in main). How this can be done? We can't actually make a char **
array because then it (obviously) fails to convert args[i].c_str()
that is of type const char *
to char *
.
The only (ugly) way I can think of is to use const_cast
to cast from const char *
to char *
.
Would anyone suggest more elegant way of doing this? I should note I can use only c++03 features.
Thanks in advance.
Upvotes: 2
Views: 3253
Reputation: 72044
It can't be done without an extra array. A const char**
means "a pointer to a pointer to const char" - so you need a place where there are actual pointers to char to point to.
So you need to create that array.
struct c_str { const char* operator ()(const std::string& s) { return s.c_str(); } };
std::vector<const char*> pointers(args.size());
std::transform(args.begin(), args.end(), pointers.begin(), c_str());
// If you really want to be compatible with argv:
pointers.push_back(0);
// &pointers[0] is what you want now
Upvotes: 4