Lets say that I have multiple functions that accomplish the same goal. An example of this would be creating a ‘constructor’ for a data type.
String new_String();
String new_String(const char *cstr);
String new_String(String s);
Obviously this cant be accomplished in C, but with functions like these (and situations where function overloading is useful) is there a convention or best practice for naming them?
Something like this?
String new_String();
String new_String_c(const char *cstr);
String new_String_s(String s);
which to me feels awkward and not easy to read. Or something like this?
String new_String();
String new_String_from_cstr(const char *str);
String new_String_copy(String s);
Which reminds me of horribly long java names because this could soon get ridiculous.
int String_last_index_of_any_characters(String s, char *chars, int length);
You can define a single “constructor” that takes a void * initialization parameter and an enum:
You could also choose to use a
...instead of avoid *. The idea is the same, but you use theva_*macros to extract the parameter if it supposed to be a string or a copy.If you just want the API to have the appearance of a single constructor, but still want type safety, you can use the techniques above to create your actual constructor implementation, and use inline functions and preprocessor tricks to give the appearance of a single constructor, with type safety.
Notice with the variadic macro,
SC_DEFAULTdoes not need a second parameter any more. At sufficient optimization levels, the code translates to just a call to the single implementation function, with the benefit of compile time type safety checks. So at the cost of some more coding on your part, you can give the user of your library the appearance of a single constructor API with all the type safety of multiple constructor functions.