【发布时间】:2020-05-31 22:14:37
【问题描述】:
编译以下人为的例子:
class Base
{};
class Derived : public Base
{};
template< typename T >
class A
{};
class B
{
public:
static void f( const A< Base >& ) {}
};
int main()
{
A< Base > tb;
A< Derived > td;
B::f( tb );
B::f( td );
return 0;
}
使用 g++-8 会出现以下错误:
error: no matching function for call to 'B::f(A<Derived>&)'
B::f( td );
note: no known conversion for argument 1 from 'A<Derived>' to 'const A<Base>&'
为什么?
既然Derived is-a Base 并且它不会覆盖任何Base 的东西,为什么我不能用Derived 代替a Base 在模板化函数参数中?
【问题讨论】:
-
A< Base >和A< Derived >是不同的、不相关的类。他们之间没有转换。它们之间根本不必有任何相似之处——它们可以有完全不同的成员。
标签: c++ templates inheritance