[英]Why is the template parameter losing constness?
I thought this is a very basic question but I could not find something similar. 我认为这是一个非常基本的问题,但我找不到类似的东西。
The following code does not compile (C3668) 以下代码无法编译(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
{
/*...*/
}
};
It will compile after removing the const from 它将在删除const后编译
void doStuff (const Param &)
What am I missing here? 我在这里错过了什么? I would expect to enforce to the
const Param& in Foo::doStuff
with my interface declaration. 我希望通过我的接口声明强制执行
const Param& in Foo::doStuff
。 Instead it seems to be removed. 相反它似乎被删除了。
The const
isn't just a text substitution, it applies to the entire type T
. const
不仅仅是文本替换,它适用于整个类型T
If T
is Param&
, const T
and const Param&
are not equivalent; 如果
T
是Param&
, const T
和const Param&
不等价; the former is the same as Param& const
, which is equivalent to Param&
. 前者与
Param& const
相同,相当于Param&
。
It becomes more obvious if you write the less common "postfix-const" form: T const
and Param const &
can't be equivalent regardless of what T
is. 如果你编写不太常见的“postfix-const”形式就会变得更加明显:无论
T
是什么, T
T const
和Param const &
都不能相等。
Thus, your "override" doesn't override anything and you get a compilation error. 因此,您的“覆盖”不会覆盖任何内容,并且您会收到编译错误。
When you have 当你有
doStuff (const T)
it is not the same type as 它与...不是同一类型
doStuff (const Param &)
The first one is a constant whatever T is so in this case you have a constant reference to a T which really doesn't make sense since references cannot be rebound. 第一个是常量,无论T是什么,所以在这种情况下,你有一个对T的恒定引用,这实际上没有意义,因为引用不能被反弹。 In the later it is a reference to a
const Param
. 在后面它是对
const Param
的引用。
What you could do is change 你能做的就是改变
struct Bar : public Foo<Param&>
to 至
struct Bar : public Foo<Param>
and then 然后
virtual void doStuff (const T) const = 0;
to 至
virtual void doStuff (const T&) const = 0;
Problem is not with const .Problem is with the override. 问题不在于const。问题与覆盖有关。 Member function declared with override doesn't override a base class member
使用override声明的成员函数不会覆盖基类成员
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.