我的模板类方法返回错误类型?

My template class method returns bad type?

本文关键字:错误 类型 返回 类方法 我的      更新时间:2023-10-16

模板类方法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;
}

(不要忘记修复好友声明。