Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a function name that is already taken

Tags:

c++

Let's assume some third-party developer writes a function

int GetErrorCode(const object * p);

This function returns only certain int values, thus I am tempted to write my own ErrorCode enum class, that contains all the possible return values. Then write a bit updated function:

enum class ErrorCode : int {};
ErrorCode GetErrorCode2(const object * p){
  return (ErrorCode)GetErrorCode(p);
}

The problem is I want my function to be named GetErrorCode and not that less-intuitive GetErrorCode2.

How can I possibly achieve that? Maybe there is a way to swap function names or something?

like image 259
user3600124 Avatar asked Aug 12 '16 18:08

user3600124


2 Answers

Use namespaces:

namespace MyLibrary {

    ErrorCode GetErrorCode(const object *p) {
        int origResult = ::ErrorCode(p); 
        // use :: to explicitly call outer function to avoid recursion
        ...
    }

}

Then you can call the function as:

MyLibrary::GetErrorCode(obj);
like image 139
Adam Trhon Avatar answered Sep 24 '22 14:09

Adam Trhon


Put your function in a namespace that you normally use. You might have a using namespace foo; - er better yet, using foo::GetErrorCode; - for it where you use it, preferably in a function's body.

like image 40
lorro Avatar answered Sep 22 '22 14:09

lorro