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 22:08

>>1
No, there's no way to do that. The best you can do is an implicit cast operator, which can be quite dangerous. Consider the following valid code:

void func(const std::string &test) {
    // cod
}

void func(int test) {
    // cod
}

void func_call() {
    func(0);
}


Because std::string has an implicit cast operator from char *, passing the integer value of 0 (which doubles as a null pointer value) will compile fine. Even worse, this confuses the function overloading.

I think I accidentally ran into this once and MSVC chose the string overload even though it made no sense to me at the time to choose that one. I'm not sure if the standard defines how this should work (I don't think it does, maybe Sepplesoxa does because it has nullptr - but then again, lol no because it still supports 0 to maintain backward compatibility), so you can bet your ass that if any two implementations perform the same way, it's a freak accident.

In short, you're much better off setting yourself up for success by not using Sepples.

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