Search code examples
c++overloadingdefault-parameters

Overloading functions only for char* and strings


I'm making some functions to save and load my values:

They are these two:

void safeFile(string &set_name) const;
void loadFile(string &set_name);

The problem here is that I also want them to work for char* so I overloaded them like this:

void safeFile(string &set_name) const;
void loadFile(string &set_name);   
void safeFile(char* set_name) const;
void loadFile(char* set_name);

In the cpp file:

void myclass::loadFile(string &set_name)
{
   ...
}
/* loadFile */


void myclass::safeFile(string &set_name)
{
   ...
}
/* safeFile*/


void myclass::loadFile(char *set_name)
{
    string mystring(set_name);
    loadFile(mystring);
}
/* loadFile */


void myclass::safeFile(char *set_name) const
{
    string mystring(set_name);
    safeFile(mystring);
}
/* safeFile*/

Is there any better or other way I should do it ? Thanks


Solution

  • Just don't add the overload for char*. saveFile and loadFile should simply take their arguments as const std::string&.

    If you had:

    void saveFile(std::string const& );
    

    You could call it with both:

    obj.saveFile("file.txt");
    obj.saveFile(std::string("file.txt"));