union word{
uint16_t value;
struct{
uint8_t low;
uint8_t high;
};
inline word(uint16_t value) noexcept
:value(value)
{}
inline word &operator=(uint16_t rhs) noexcept{
value = rhs;
return *this;
}
inline operator uint16_t() const noexcept{
return value;
}
}
下位バイトと上位バイトに簡単にアクセスできるリトルエンディアンの 2 バイト型を定義しようとしています。さらに、算術演算子を呼び出すときに、「単語」型が完全に uint16_t のように動作するようにします。したがって、uint16_t の型キャスト演算子をオーバーロードしました。
しかし、私はわずかな問題に遭遇しました:
word w1 = 5;
w1 = w1 + w1; //this works fine due to implicit conversion
w1 += w1; //fails to compile. lhs will not implicitly convert
コンパイルに失敗する理由がわかりました。+=、-=、&=、|= などのすべての算術演算子のオーバーロードを回避したいのですが、すべての演算子を定義する必要を回避する方法はありますか? それらのほとんどが必要になる可能性があります。
どうもありがとうございました!