C++ Extract std::string from a variable-length argument list
Hey everyone! I'm trying to make a simple copy of sprintf that returns the formatted string, but I am coming into a small snag...
Apparently, using a variable-length argument list you cannot pass a std::string instance.
I already have the parser working properly with int, double, float, char, const char*, char*... I have yet to get strings to work. :\
In case you're wondering, this is the compile error I get: /root/learncpp/StringFormat/main.cpp:8: warning: cannot pass objects of non-POD type 'struct std::string' through '...'; call will abort at runtime
The main reason I'm doing this is so that I can have convenient formatting without having to rely on 3rd party libraries, yet still not have to append ".c_str()" to every string instance I use.
Help with this would be appreciated. Perhaps there's a different version of variable-length argument lists made specifically for C++?
EDIT: I have just realized, if you pass a pointer to a string (i.e. using the & prefix) it works well. All you have to do is dereference a string pointer in the custom sprintf, while passing the address of the std::string!
Still, it would be nice to see if there's any way t开发者_StackOverflow中文版o support string directly through variable-length argument lists. Thanks!
No -- as the compiler said, you're only allowed to pass objects of POD type to a variadic function.
What you normally want to do is eliminate using a variadic function in the first place, such as by using an iostream instead of something like printf (or a stringstream instead of sprintf).
精彩评论