C++ 隐式转换运算符不';t使用运算符重载启动
考虑以下示例:C++ 隐式转换运算符不';t使用运算符重载启动,c++,c++11,operator-overloading,conversion-operator,C++,C++11,Operator Overloading,Conversion Operator,考虑以下示例: #include <string> #include <sstream> struct Location { unsigned line; template<typename CharT, typename Traits> operator std::basic_string<CharT, Traits>() const { std::basic_ostringstream<Char
#include <string>
#include <sstream>
struct Location {
unsigned line;
template<typename CharT, typename Traits>
operator std::basic_string<CharT, Traits>() const {
std::basic_ostringstream<CharT, Traits> ss;
ss << line;
return ss.str();
}
};
int main()
{
using namespace std::string_literals;
Location loc{42};
std::string s1 = "Line: "s.append(loc) + "\n"s; // fine
//std::string s2 = "Line: "s + loc + "\n"s; // error
}
#包括
#包括
结构位置{
无符号线;
模板
运算符std::basic_string()常量{
std::基本流ss;
ss显式转换到std::string对我有用:
您的运算符是模板化的,因此需要推导模板参数。您不能这样做,因为编译器试图将basic_string
匹配到您的位置,但失败了
所以问题在于重载,而不是转换,因为代码实际上从未达到那个点
更改此项:
std::string s2 = "Line: "s + loc + "\n"s;
为此:
std::string s2 = "Line: "s + std::string(loc) + "\n"s;
您应该很好,因为如果仔细查看编译器错误,它会提到:
template argument deduction/substitution failed:
prog.cc:22:32: note: 'Location' is not derived from 'const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>'
std::string s2 = "Line: "s + loc + "\n"s; // error
^~~
模板参数推导/替换失败:
prog.cc:22:32:注意:“Location”不是从“const std::u cxx11::basic_string”派生而来的
std::string s2=“行:”s+loc+“\n”s;//错误
^~~
和其他类似的消息。很抱歉,我看不到有效的代码。什么是s
?@gsamaras Right@Holt,谢谢!这里的问题是,当您执行.append
时,模板参数已经在行的构造过程中实例化了s
,因此没有发生模板参数推断(.append
需要std::string
),但+
运算符是模板化的,因此您需要推断图表
、特征
和分配器
,而您不能,因为编译器无法将基本字符串
与位置
进行匹配-您甚至还没有达到转换阶段,是过载阶段失败了。@Holt谢谢。一项技术所有的解释都是我想要的。如果你发布完整的答案,我会接受。
template argument deduction/substitution failed:
prog.cc:22:32: note: 'Location' is not derived from 'const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>'
std::string s2 = "Line: "s + loc + "\n"s; // error
^~~