I want to overload a function with the same type parameter; what should I do?
https://softwareengineering.stackexchange.com/questions/307276
-
11-12-2020 - |
Pergunta
I'm creating an API, and I want to overload a function for strip
:
QString MyClass::strip();
QString MyClass::strip(QRegularExpression open);
QString MyClass::strip(QRegularExpression close);
QString MyClass::strip(QRegularExpression open, QRegularExpression close);
Obviously the second and third conflict.
What is the recommended style for C++ and Qt programmers to restructure this?
Solução
What about creating a class to hold your arguments? This class would contain both open
and close
parameters and either of them could be NULL
. Then, there will be only one strip
method with above class as argument and method will decide if it wants to use open
/close
if they are set.
Outras dicas
There are many options, it's your tradeoff which to take:
Decision at runtime:
Add a defaulted
bool
argument:QString MyClass::strip(QRegularExpression regex, bool close=false); // Mimic the two-regex-variants interface as good as possible
Use scoped enum's and no default as a variant on 1 which is more descriptive:
enum class option { open, close }; QString MyClass::strip(QRegularExpression regex, option open_close);
Use
std::experimental::optional
or something like that, maybe from boost.Find out that a specific regex does nothing, and document that as the no-op default.
Decision at compiletime:
Use overloads replacing one argument with
std::nullptr_t
:QString MyClass::strip(std::nullptr_t open, QRegularExpression close); QString MyClass::strip(QRegularExpression open, std::nullptr_t close = {});
Use tags to avoid any overhead:
constexpr struct open_t {} open; constexpr struct close_t {} close; QString MyClass::strip(open_t, QRegularExpression regex); QString MyClass::strip(close_t, QRegularExpression regex); // Call it like this: object.strip(object.open, regex);
Bite the bullet and name those functions differently:
QString MyClass::strip_open(QRegularExpression regex); QString MyClass::strip_close(QRegularExpression regex);
Consider whether making the open-regex and the close-regex different types makes sense. To be truthful, I doubt it here, but where appropriate that's the best option.
I would suggest
QString MyClass::strip();
QString MyClass::strip(QRegularExpression regex, bool opening=false);
QString MyClass::strip(QRegularExpression open, QRegularExpression close);
and perhaps
QString MyClass::strip_open(QRegularExpression regex);
QString MyClass::strip_close(QRegularExpression regex);
or replace the bool opening
with e.g.
enum stripping_mode {Strip_Open, Strip_Close};;
or make even it a class enum