Corvus Corax
Corvus Corax

Reputation: 231

Overloading standard mathematical functions for custom types

Suppose I'm writing a class representing a mathematical object for which it makes sense to define various standard operations.

By overloading the arithmetical operators I can enjoy the fact that any templated algorithm using them will work as expected when given my class. But what if the algorithm uses something like std::pow?

The standard seems to state that only template specializations of functions in the std namespace are allowed, meaning that I am not allowed to write my own overload of std::pow for my class. But if that's really the case, what's the best approach to ensure genericity nevertheless?

Upvotes: 6

Views: 465

Answers (1)

MSalters
MSalters

Reputation: 179991

Yakk's comment is the right answer. You put your pow in your namespace, just like the standard put its pow in std::. Argument Dependent Lookup means that pow(x,y) will look in the namespaces of the types of x and y.

Experienced library writers know how to use ADL effectively, but TBH I wouldn't immediately know a library that has good reason to call pow on objects of unknown type.

Upvotes: 4

Related Questions