views:

168

answers:

4

Is it possible to overload a method on default parameters?

For example, if I have a method split() to split a string, but the string has two delimiters, say '_' and "delimit". Can I have two methods something like:

split(const char *str, char delim = ' ')

and

split(const char *str, const char* delim = "delimit");

Or, is there a better way of achieving this? Somehow, my brain isn't working now and am unable to think of any other solution.

Edit: The problem in detail:

I have a string with two delimiters, say for example, nativeProbableCause_Complete|Alarm|Text. I need to separate nativeProbableCause and Complete|Alarm|Text and then further, I need to separate Complete|Alarm|Text into individual words and join them back with space as a separator sometime later (for which I already have written a utility and isn't a big deal). It is only the separation of the delimited string that is troubling me.

+4  A: 

No, you cant - if you think about it, the notion of a default means 'use this unless I say otherwise'. If the compiler has 2 options for a default, which one will it choose?

Visage
+1  A: 

How about implementing as 2 different methods like

  • split_with_default_delimiter_space
  • split_with_default_delimiter_delimit

Personally I'd prefer using something like this (more readable.. intent conveying) over the type of overloading that you mentioned... even if it was somehow possible for the compiler to do that.

Gishu
A: 

You could use a version of split that accepts a variable number of delimiters (split(const char*,vector<string>), if you want to split(const char*, const char**)) or just use Boost Tokenizer.

tstenner
I can't use boost here in the project... that's the worst part. :(
Shree
+1  A: 

Why not just call split() twice and explicitly pass the delimiter the second time? Will delimiters always be single characters?

Do you perform any other processing on the 2nd set of words before joining them? If not, then for the second task what you really want to do is replace substrings. This is most easily done with std::string::find and std::string::replace. If you must use c-strings, you could use strstr/strchr/strpbrk, strcpy and strcat, or use just strstr/strchr/strpbrk and join them in place.

outis