c++ - string to char* conversion -
i in code base there lots of function calls functions take pointer argument. however, function call passes "string" object if it's pointer. following code shown give idea.
#include <vector> #include <unordered_map> #include <iostream> #include <stdlib.h> #include <string.h> #include <string> using namespace std; void dum(char *s) { printf("%s\n", s); } operator char* (string s) { return s.c_str(); } int main(int argc,char *argv[]) { string st("hello world"); dum(st); return 0; }
i not allowed change syntax these functions or function calls. 1 possible solution came add operator overload, unfortunately doesn't work, here error g++ (ver 4.7.3), command line: g++ -std=c++11 te2.cc
error: ‘operator char*(std::string)’ must nonstatic member function
any ideas? thanks.
update1
@ferruccio's answer reminded me mention there function calls like
dum(dum2());
where dum2() function like:
string dum2() { string s; //..... return s; }
so wrapper following doesn't work (), compiler gives error no matching function call ‘dum(std::string)’
void dum(string &s) { dum(s.c_str()); }
you add simple function overload each function takes char*
. e.g.
void dum(const string& s) { dum(s.c_str()); }
Comments
Post a Comment