C++ - 自动转换为 std::string

标签 c++ c++11 casting

我有这个代码

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/

相关文章:

c++ - 在 3D 中可视化点、线和三角形(C++ API 和文件格式)

c++ - 如何运行一些每 2 秒在不同线程上运行的方法?

java - 将最终类转换为该类未声明实现的兼容接口(interface)

c++ - 为什么允许将 void* 的 static_cast 转换为另一种类型?

c++ - QTimer::singleShot 仅在间隔为 0 时调用 lambda

ios - Swift - 任意数组到字符串数组

c++ - 这个不可复制的 map 是否合法 c++11? GCC 4.7 和 MSVS 2010 允许它。 Clang 3.1 没有

c++ - 作为函数参数的字符串对的 C++ vector 的默认规范在 gcc-4.1.2 上无效?

c++ - 通过迭代器修改 std::set 元素:为什么我的代码没有编译?

c++ - to_string 不是 std 的成员,g++ (mingw) 说