Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading standard mathematical functions for custom types

Tags:

c++

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?

like image 810
Corvus Corax Avatar asked Oct 21 '22 15:10

Corvus Corax


1 Answers

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.

like image 56
MSalters Avatar answered Oct 23 '22 15:10

MSalters