模板类方法return_self必须返回类型为Class<string>
的对象 .但是,它返回Class<basic_string<char>>
为什么,请查看我的代码
using namespace std;
template <typename Type>
struct Class;
template <typename Type>
ostream& operator<<(ostream& os, Class<Type>& ref){
os << ref.value;
return os;
}
template <typename Type>
struct Class{
Type value;
Class(Type val): value{val}{}
// Returns bad Type
Class<Type> return_self(){
return *this;
}
friend ostream& operator<<<Type>(ostream&, Class<Type>&);
};
int main(){
Class<string> obj{"How are you"};
cout << obj << endl; // This one works fine
cout << obj.return_self() << endl; // Error occurs here
}
std::string
被定义为std::basic_string<char>
的别名,因此它们实际上是同一类型。 这不是程序编译失败的原因。
问题是obj.return_self()
表示临时引用,并且临时引用不能绑定到非常量引用,例如operator<<
函数中的ref
参数。
您将在这段代码中观察到完全相同的错误,它具有相同的问题(尝试将临时引用绑定到非常量引用(:
cout << Class<string>{"How are you"} << endl;
解决方案是将ref
作为常量引用:
template <typename Type>
ostream& operator<<(ostream& os, Class<Type> const & ref){
os << ref.value;
return os;
}
(不要忘记修复好友声明。