FERcsI
FERcsI

Reputation: 410

Specialize C++ template for different but still same types

I would like to specialize a template for two types which of both are based on the same basic type:

using myint=uint16_t; //16 bit integer
using myfxpt=uint16_t //8+8 bit fix point number

It is not possible to specialize a template for both, because both are uint16_t. However, according to the representation they are still different.

How could I find a workaround for this issue? Using a somehow transparent fixpoint class could also be a solution, but effectiveness is important. I don't know how I could write it so that after the compiler's optimization we got the same result.

Upvotes: 0

Views: 65

Answers (1)

Filipp
Filipp

Reputation: 2040

What you want are strong typedefs. C++ does not have them. Various proposals to add them have been made, but they raise questions to which there are no clear resolutions. For now, one way to fake it is to use enum classes:

enum class myfxpt : uint16_t {};

constexpr myfxpt operator+(myfxpt lhs, myfxpt rhs) noexcept {
    return myfxpt{static_cast<uint16_t>(lhs) + static_cast<uint16_t>(rhs)};
}
constexpr myfxpt operator-(myfxpt lhs, myfxpt rhs) noexcept {
    return myfxpt{static_cast<uint16_t>(lhs) - static_cast<uint16_t>(rhs)};
}
// Same for all the operators you care about. Same for myint. Maybe use macros?

Written this way, for all optimization levels above -O0 any compiler will optimize the operations as if they were directly on the underlying type.

Upvotes: 1

Related Questions