我有這樣的代碼C++ - 汽車鑄件的std :: string
template <typename T>
class KeyValueProperty {
protected:
T value = T();
std::string key = "";
public:
KeyValueProperty(const std::string & key) : key(key) { }
T & operator = (const T &i) { return value = i; };
operator const T &(){ return value; };
};
struct T2 {
KeyValueProperty<std::string> x {"x"};
KeyValueProperty<double> y {"y"};
};
,並在主
T2 tx;
tx.x = "hellow";
tx.y = 10;
std::cout << static_cast<std::string>(tx.x) << ::std::endl;
std::cout << tx.y << ::std::endl;
這是正常工作。但是,這樣做只是這
std::cout << tx.x << ::std::endl;
將在
錯誤C2679結束:二進制「< <」:沒有操作員發現這需要類型的右手操作數‘測試:: KeyValueProperty’(或 沒有可接受的轉換)
是否有可能進行自動轉換,或者我必須手動調用鑄造?
但是,即使沒有這個,爲什麼雙重輸出呢? –
@MartinPerry KeyValueProperty對T&隱式轉換運算符。 –
但是,爲什麼這個隱式轉換對於std :: string不起作用,如果它是用於double的呢? –