为什么模板参数会丢失常量?

Lar*_*een 6 c++ templates interface

我认为这是一个非常基本的问题,但我找不到类似的东西.

以下代码无法编译(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
    {
        /*...*/
    }
};
Run Code Online (Sandbox Code Playgroud)

它将在删除const后编译

void doStuff (const Param &)
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?我希望const Param& in Foo::doStuff通过我的界面声明强制执行.相反它似乎被删除了.

mol*_*ilo 5

const不仅仅是文本替换,它适用于整个类型T.

如果TParam&,const T并且const Param&不等同; 前者是相同的Param& const,相当于Param&.
如果你写的不太常见的"后缀const的"形式变得更加明显:T constParam const &不能等同不管是什么T是.

因此,您的"覆盖"不会覆盖任何内容,并且您会收到编译错误.