请考虑以下代码.
struct foo
{
};
template<typename T>
class test
{
public:
test() {}
const T& value() const
{
return f;
}
private:
T f;
};
int main()
{
const test<foo*> t;
foo* f = t.value();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
t是一个const变量,value()是一个返回的常量成员函数const T&.AFAIK,const类型不能分配给非const类型.但如何foo* f = t.value();编译好.如何发生这种情况以及如何确保value()只能分配给const foo*?
编辑
我发现,这是在使用模板时发生的.以下代码按预期工作.
class test
{
public:
test() {}
const foo* value() const { return f; }
private:
foo* f;
};
int …Run Code Online (Sandbox Code Playgroud)