【发布时间】:2010-02-20 18:33:53
【问题描述】:
请考虑以下代码。
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;
}
t 是一个const 变量,value() 是一个返回const T& 的常量成员函数。 AFAIK,const 类型不能分配给非常量类型。但是foo* f = t.value(); 如何编译得很好。这是怎么发生的?如何确保value() 只能分配给const foo*?
编辑
我发现,这是在使用模板时发生的。以下代码按预期工作。
class test
{
public:
test() {}
const foo* value() const { return f; }
private:
foo* f;
};
int main()
{
const test t;
foo* f = t.value(); // error here
return 0;
}
为什么在使用模板时会出现问题?
【问题讨论】:
标签: c++ constants const-correctness