how to define a pointer cast operator?

You're almost there, the correct syntax for the operator definition is:

operator const int32_t*() const { return &int32_storage_; }
operator const int64_t*() const { return &int64_storage_; }

Also note that as described here, you can also make these operators explicit, which is often desired to guard against unwanted conversions. It requires more verbosity, when doing the conversion, e.g. static_cast<const int32_t*>(a) instead of just a.


When you want the type to implicitly convert into another you have to declare that as an operator method:

operator const int32_t*() const { return &int32_storage_; }
operator const int64_t*() const { return &int64_storage_; }

Now, in order to call the functions just say a, b and they are implicitly converted:

std::cout << "32bit a + b = " << int32_add(a, b) << std::endl;
std::cout << "32bit a + b = " << int64_add(a, b) << std::endl;

Note: your function qualifiers aren't consistent (const int32_t*)

they all should be const T* const

also std::endl is generally wrong, replace it with '\n' - reasoning

Tags:

C++