2017-08-24 6 views
2

私は以下の演算子が定義されました:クラス定義外の演算子のオーバーロードを優先するには?

std::vector<uint8_t> &operator<<(std::vector<uint8_t> &bytes, uint8_t b); 
std::vector<uint8_t> &operator<<(std::vector<uint8_t> &bytes, uint32_t b); 

intとオペレーターを呼び出すときに、私はエラーを取得:

/misc.hpp:77:12: error: ambiguous overload for ‘operator<<’ (operand types are ‘std::vector<unsigned char>’ and ‘int’) 
    buffer << first; 
    ~~~~~~~^~~~~~~~ 
./misc.hpp:62:23: note: candidate: std::vector<unsigned char>& operator<<(std::vector<unsigned char>&, uint8_t) 
std::vector<uint8_t> &operator<<(std::vector<uint8_t> &bytes, uint8_t b); 
         ^~~~~~~~ 
./misc.hpp:63:23: note: candidate: std::vector<unsigned char>& operator<<(std::vector<unsigned char>&, uint32_t) 
std::vector<uint8_t> &operator<<(std::vector<uint8_t> &bytes, uint32_t b); 

私はuint8_t版が優先させることができ、Iドンように、その演算子を呼び出すには、型キャストが必要です(例:static_cast<uint8_t>)。

+0

これらのオーバーロードはどのように異なるのですか?なぜただ一つしかないのですか? – LogicStuff

+1

@RustyXこれは絶対に間違っています。 C++ではなく、標準より前のCルールについて考えています。 – Quentin

+0

正直なところ、 'static_cast 'は、あなたが望むものを達成するための本当にクリーンな方法です。 – AndyG

答えて

3

あなたは二番目にテンプレートを作成することによってそれをハック可能性:

std::vector<uint8_t> &operator<<(std::vector<uint8_t> &bytes, uint8_t b); 

template<class Y> 
std::vector<uint8_t> &operator<<(std::vector<uint8_t> &bytes, Y b); 

オーバーロードの解決は、必ずテンプレート1の上に非テンプレート関数を好むだろうので、この技術は、適切な階層を紹介しています。もし、Yの型が放出されたくない場合は、Y型の静的アサーションに頼ります。

実際、intへのさらに多くのオーバーロードはおそらく分かりやすいことです。

+0

ありがとう - あなたはY型の静的アサーションを行う方法の小さな例を詳しく説明しますか?私はあなたの考えが良いと思う... – Shuzheng

関連する問題