隐式类型转换不起作用
Implicit type conversion is not working
class Test {
public:
operator string() {
return string{"TEST!"};
}
};
int main() {
cout << Test{};
}
我期待 Test 对象将隐式转换为字符串和输出,但它给了我错误:
error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
此显式转换有效:
cout << string{Test{}};
我通过投射到const char*
让它工作:
class Test {
public:
operator const char*() {
return "TEST!";
}
};
然后输出:
cout << Test{}; //Yay it works.
我假设cout << string
已经是从string
到char *
的隐式转换,如果我使用强制转换为字符串,它不会从Test to string to char *
执行两级转换。直接投射到const char*
后,就可以工作了。(如果假设错误,请更正(
证明假设是正确的
class Test {
public:
operator string() {
return string{"TEST!"};
}
};
ostream& operator<< (ostream& os, string s){
os << s;
return os;
}
这将从Test to string
和输出字符串中执行直接类型推导。 在我尝试之后,它有效!
cout << Test{}; //YAY WORKS! OUTPUT "TEST!"
Borgleader
解释了cout << string
的一些特别之处。假设部分正确,部分错误。
explicit
关键字意味着您必须像std::string(Test{})
一样自己显式进行转换。它禁用隐式转换。
cout << string{Test{}}; // <-- this is explicit, you've got implicit and explicit confused
规则是,在模板参数推导期间,不会尝试用户定义的转换。但是,正如您所指出的,如果您只有一个转换运算符来编译它。这是因为该重载不是函数模板。看看参考页面,你会看到:
basic_ostream& operator<<( int value );
这是一个非模板化的重载,因此编译器将查找用户定义的转换。
采用std::string
(或std::basic_string
(的operator<<
重载是一个函数模板。在模板参数推导期间不考虑用户定义的转换,因此编译器不认为string
重载是匹配的。
若要避免此错误,请为类定义重载basic_ostream& operator<<(basic_ostream&, Test&)
。
相关文章:
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 嘿,我正在尝试将此c ++转换为javascript,但有些东西不起作用
- 当我使用自定义类型创建动态数组时,即使使用字符串,它似乎也不起作用
- C++ 模板类型检查标准::is_same不起作用?
- C++实用程序::转换在静态链接库中不起作用
- 没有类型结构绑定不起作用?
- "+=" 操作在类型之间不起作用 std::复杂<double>和__complex__双精度
- 模板 ctor 类型推导不起作用(没有匹配的构造函数用于初始化 ...)与函数<>参数
- 将 cmake 代码段转换为函数 - 不起作用
- 自定义类型转换运算符在转发引用上调用时不起作用(当对象按值传递时有效)
- 我的代码在作为参数传入 .begin() 时不起作用,但在我将 .begin() 转换为迭代器后工作
- 从 C++ 转换的 C# 代码不起作用
- 句子转换器在存在新行的情况下不起作用
- 模板参数类型推导在函数对象中不起作用
- 为什么隐式转换在累积中不起作用?
- 将向量的大小()转换为 int 不起作用
- 为什么转换不起作用
- pybind11:Python 到 C++ 数据类型转换不起作用
- 在 C++ 中使用构造函数进行类型转换不起作用?
- 隐式类型转换不起作用