packetie
packetie

Reputation: 5069

string to char* conversion

I am in a code base where there are lots of function calls to functions that take a pointer as an argument. However, the function call passes a "string" object as if it's pointer. The following code is shown to give you an 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 am not allowed to change the syntax for all these functions or function calls. One possible solution I came up is to add a operator overload, but unfortunately it doesn't work, here is the error from g++ (ver 4.7.3), command line: g++ -std=c++11 te2.cc

error: ‘operator char*(std::string)’ must be a nonstatic member function

Any ideas? Thanks.

UPDATE1

@ferruccio's answer reminded me to mention that there are function calls like

dum(dum2());

where dum2() is a function is like:

string dum2() {
    string s;
    //.....
    return s;
}

So the wrapper like the following doesn't work (), compiler gives error no matching function for call to ‘dum(std::string)’

void dum(string &s) {
    dum(s.c_str());
}

Upvotes: 1

Views: 90

Answers (2)

Ferruccio
Ferruccio

Reputation: 100728

You could add a simple function overload for each function that takes a char*. e.g.

void dum(const string& s) {
    dum(s.c_str());
}

Upvotes: 3

David Schwartz
David Schwartz

Reputation: 182837

operator char* (string s) {
    return s.c_str();
}

This is broken (if it was allowed). When this function returns, s no longer exists. So a pointer to its contents is of no use.

Upvotes: 4

Related Questions