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?

Foi útil?

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:

  1. Add a defaulted bool argument:

    QString MyClass::strip(QRegularExpression regex, bool close=false);
    // Mimic the two-regex-variants interface as good as possible
    
  2. 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);
    
  3. Use std::experimental::optional or something like that, maybe from boost.

  4. Find out that a specific regex does nothing, and document that as the no-op default.

Decision at compiletime:

  1. 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 = {});
    
  2. 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);
    
  3. Bite the bullet and name those functions differently:

    QString MyClass::strip_open(QRegularExpression regex);
    QString MyClass::strip_close(QRegularExpression regex);
    
  4. 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

Licenciado em: CC-BY-SA com atribuição
scroll top