仅仅定义从模板类派生的类是不够的

Defining class derived from template class is not enough

本文关键字:不够 派生 定义      更新时间:2023-10-16

"A.h">

template<class T>
struct A 
{
    void foo();
};
template<class T>
struct B : A<T> {};

"A.cpp">

template<class T>
void A<T>::foo()
{
}
template struct B<int>;

当我在其他源文件中调用B的方法foo时,由于未解析的外部符号,它不会构建。为什么A不能用B来定义?至少我觉得这很奇怪。有没有办法从B的定义中强制a的定义?我尝试在结构B中添加"usingA::foo;",但它没有改变任何内容。

我知道我可以简单地定义A,但我不想这样做,因为在我的真实代码中,"A"包含的模板参数比"B"更多,我担心我会犯错误,直到有人编写需要这些未解决方法的代码时才会被检测到。我也很好奇为什么它不起作用。

在.h文件中定义A::foo。

A.h

template<class T>
struct A 
{
    void foo();
};
template<class T>
struct B : A<T> {};
template<class T>
void A<T>::foo()
{
}

A.cpp

template struct B<int>;