2
オーバーロード演算子+を混在型で使用したい。 非テンプレートクラスに問題はありません。 テンプレートクラスで動作させるには、フレンド operator + inside classを追加しました。テンプレートと組み込みコンストラクタのクラス定義の外にあるフレンド宣言
template <typename T> class Wrapper
{
T _val;
public:
Wrapper(T val) :_val(val){}
T getValue() const { return _val; }
friend Wrapper<T> operator+(const Wrapper<T>& val1, const Wrapper<T>& val2)
{
return Wrapper<T>(val1.getValue() + val2.getValue());
}
};
int main()
{
Wrapper<int> v1 = 10; // OK, implicit constructor
Wrapper<int> v2(20);
Wrapper<int> result1 = v1 + v2; // OK, both values are of type Wrapper<int>
Wrapper<int> result2 = v1 + 40; // Ok, casting by implicit constructor works
return 0;
}
は今、私はこのようなクラスの外にオペレータ+実装を移動したい:
#include <iostream>
#include <string>
template <typename T> class Wrapper;
template <typename T> Wrapper<T> operator+(const Wrapper<T>& val1, const Wrapper<T>& val2);
template <typename T> class Wrapper
{
T _val;
public:
Wrapper(T val) :_val(val){}
T getValue() const { return _val; }
friend Wrapper<T> operator+ <>(const Wrapper<T>& val1, const Wrapper<T>& val2);
};
// template<class T> Wrapper<T> operator+(const Wrapper<T>&, const Wrapper<T>&)
// template argument deduction/substitution failed
template <typename T> Wrapper<T> operator+(const Wrapper<T>& val1, const Wrapper<T>& val2)
{
return Wrapper<T>(val1.getValue() + val2.getValue());
}
int main()
{
Wrapper<int> v1 = 10; // OK, implicit constructor
Wrapper<int> v2(20);
Wrapper<int> result1 = v1 + v2; // OK, both values are of type Wrapper<int>
// note: mismatched types 'const Wrapper<T>' and 'int'
Wrapper<int> result2 = v1 + 40; // Error
return 0;
}
が、それは私がエラー(上記のコードにそれらを貼り付け)をコンパイル与えます。 修正できますか? (動作しない)(作業)
http://cpp.sh/5j5zg http://cpp.sh/9saow
男、感謝 – amplifier
【関連質問](https://stackoverflow.com/questions/9787593)、うん@justin。その短いことは、考えられるすべてのテンプレートインスタンス化をコンパイラがテストして、あなたが探している暗黙の変換をサポートしているかどうかを調べることではないということです。 –
関連:https://stackoverflow.com/a/4661372/1896169 – Justin