Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C++/STL Wankery

Name: Anonymous 2011-02-15 19:11

In C++, can I define a typecast operator for converting (both ways) between std::string and const char *?

In the end, I just want to avoid having to declare every function twice:


   void func1(const char *x) { func1(std::string(x)); }
   void func1(std::string x);

   void func2(const char *x) { func2(std::string(x)); }
   void func2(std::string x);

   void func3(const char *x) { func3(std::string(x)); }
   void func3(std::string x);

Name: Anonymous 2011-02-16 19:31

Conforming std::string implementations have an implicit constructor that accepts a char const*, so all you have to do is write functions that accept std::string, and you can pass char*'s and string literals to it.

As for the other way around, it should be up to the programmer to call std::string::c_str explicitly when a char* is needed. If you don't like it, then that means you've probably got autism/obsessive-compulsive disorder.

The following code should work. If it does not, your compiler/standard library is probably old-ass fucking shit and it's time to upgrade.


void func_sepples(std::string x) {
// abstract bullshite
}

void func_holy_shit(char const* x) {
// abstract bullshite
}

int main() {
    std::string s("faggot");
    func_sepples("fuck you");
    func_holy_shit(s.c_str());
    return 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List