我有这个代码
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;
将结束于
error C2679: binary '<<': no operator found which takes a right-hand operand of type 'Test::KeyValueProperty' (or there is no acceptable conversion)
是否可以自动转换,或者我必须手动调用转换?
最佳答案
原因t.y
即使没有自定义也能工作 operator<<
是因为已经存在一个operator<<(std::ostream&, double)
, 编译器也可以看到它可以生成 double
离开你的类(class)。它这样做了,我们很高兴。
但是,没有operator<<(std::ostream&, std::string)
.如果有,同样的逻辑也适用,我们仍然会很高兴。相反,有:
template <class CharT, class Traits, class Allocator>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os,
const std::basic_string<CharT, Traits, Allocator>& str);
也就是说,任何类型的 basic_string
的通用插入运算符.
虽然存在一些模板参数可以使它看起来像 operator<<(std::ostream&, std::string)
,编译器不会尝试猜测哪些可能的模板参数将允许它随后将您的类转换为结果。组合太多,所以这是不允许的。
这就是为什么你必须明确地将你的对象变成一个 std::string
(又名 std::basic_string<char>
)- 这从问题中移除了一层,它可以进行常规的旧类型推导以完成这项工作。
正确的解决方案是为您的包装类提供一个插入运算符,以回避这个问题。
关于C++ - 自动转换为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46861048/