c++namespacesoverloading

Is it bad idea to add new functions into an existing 3rd party library's namespace?


My code is using a library called "tf2" and it has a namespace of tf2 and overloaded functions like tf2:fromMsg().

Then in my code, I would like to add one more overloaded function tf2:fromMsg() but with difference parameters.

So I write code like this: (in my own code)

namespace tf2
{
void fromMsg(const geometry_msgs::msg::PoseStamped & msg, tf2::Stamped<tf2::Transform> & out)
{
  ...
}
}  // namespace tf2

I see some benefits, so that the user of my code use familiar tf:frmMsg() like other code which already uses tf:frmMsg().

But I also see some concerns: the code is actually hacking into the existing namespace and pretending it's a whole part but actually it's not.

So, is it good or bad?


Solution

  • Bad idea.

    At some point in the future, it may violate the "One Definition Rule" and lead to undefined behavior.

    You can use the using clause to help simplify things:

    namespace tf2Extension
    {
    void fromMsg(const geometry_msgs::msg::PoseStamped & msg, tf2::Stamped<tf2::Transform> & out)
    {
      ...
    }
    }
    
    .....
    
    void myFunction()
    {
        using  tf2Extension::fromMsg;
        using  tf2::fromMsg;
    
        fromMsg(<Parameters That distinguish usage>);
    }
    

    Now the compiler will tell you when the tf2 library is extended and clashes with your function.