![](/img/trans.png)
[英]Why does template parameter deduction for T 'skips' the constness of array elements when function parameter is const reference to T?
[英]Why is the template parameter losing constness?
我认为这是一个非常基本的问题,但我找不到类似的东西。
以下代码无法编译(C3668)
struct Param
{
int a;
int b;
};
template <typename T>
struct Foo
{
virtual void doStuff (const T) const = 0;
};
struct Bar : public Foo<Param&>
{
void doStuff (const Param &) const override
{
/*...*/
}
};
它将在删除const后编译
void doStuff (const Param &)
我在这里错过了什么? 我希望通过我的接口声明强制执行const Param& in Foo::doStuff
。 相反它似乎被删除了。
const
不仅仅是文本替换,它适用于整个类型T
如果T
是Param&
, const T
和const Param&
不等价; 前者与Param& const
相同,相当于Param&
。
如果你编写不太常见的“postfix-const”形式就会变得更加明显:无论T
是什么, T
T const
和Param const &
都不能相等。
因此,您的“覆盖”不会覆盖任何内容,并且您会收到编译错误。
当你有
doStuff (const T)
它与...不是同一类型
doStuff (const Param &)
第一个是常量,无论T是什么,所以在这种情况下,你有一个对T的恒定引用,这实际上没有意义,因为引用不能被反弹。 在后面它是对const Param
的引用。
你能做的就是改变
struct Bar : public Foo<Param&>
至
struct Bar : public Foo<Param>
然后
virtual void doStuff (const T) const = 0;
至
virtual void doStuff (const T&) const = 0;
问题不在于const。问题与覆盖有关。 使用override声明的成员函数不会覆盖基类成员
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.