C++ allows aggressive optimization with arithmetic math expressions for the standard data types (builtin integer and floating point types). In these cases, while adhering to the C++ standard, the compiler can precompute literal constants, reorder operations, even change the operations completely, etc. (and in some cases even deviate from the standard compliance, as what happens with the -Ofast
optimization level in some compilers, for example).
But now let's suppose you write your custom classes library for scalars and you implement the arithmetic operators for them, and even your own user-defined literals for constants definition.
Does the C++ specification provide some mechanism for achieving in the operators of your own classes the same optimization chances as for the builtin integer and floating point types?
Imagine for example you have the following:
#include <cstdint>
class MyFP16
{
private:
std::uint16_t m_val;
public:
MyFP16();
[...other constructors here...]
~MyFP16();
// Arithmetic operators
friend MyFP16 operator+(const MyFP16 &c1, const MyFP16 &c2);
friend MyFP16 operator-(const MyFP16 &c1, const MyFP16 &c2);
friend MyFP16 operator*(const MyFP16 &c1, const MyFP16 &c2);
friend MyFP16 operator/(const MyFP16 &c1, const MyFP16 &c2);
[...rest of arithmetic operators...]
// Other logic needed
[...]
};
Can I define this class in a way that all operators have exactly the same semantics as in the float
builtin type, so that all the arithmetic expressions optimizations that can be used for float
can be used also for my class, taking advantage of reordering operations, commutativity/associativity, transforming some operations into others, precomputing constants results, etc...? How?
Thanks a lot!