从我在这里发布的上一个示例中,关于何时template
实例化?,我得到的答案是只有在使用模板时,编译器才会实例化它。但是看看这个例子:
template <typename T>
struct Pow{
T operator()(T const& x){ return x * x; }
};
extern template struct Pow<int>; // explicit instantiation declaration
struct Foo{
Pow<int> pi{};
void fn(Pow<int>);
};
void Foo::fn(Pow<int> pw){
// std::cout << pw(7) << '\n';
}
void bar(Pow<int> pwi){
// std::cout << pwi(10) << '\n';
}
int main(){
Foo f;
}
正如你所看到的,我已经声明了一个显式的模板实例化
Pow<int>
,但还没有定义它。该程序运行良好,不会抱怨缺少Pow<int>
!在上一个主题中,如果我使用模板类型作为函数定义(而不是声明)的参数类型,那么模板会被实例化,但在这里你可以看到:定义了成员函数和
Foo::fn(Pow<int>)
普通函数函数bar(Pow<int>)
但编译器不会抱怨Pow<int>
?!!!如果我取消注释上述函数中的行,程序将无法编译。那么这是否意味着
Pow<int>
在函数定义中用作函数参数和像 in 中的成员数据时不实例化Foo::Pow<int> pi{};
?我觉得很混乱:
void f(Pow<int>); // function declaration: Pow<int> is not instantiated yet. void f2(Pow<int>){} // function definition: Pow<int> instantiated? void f3(pow<int> Pwi){ std::cout << Pwi(10);} // function definition and usage of `Pow<int>`: Pow<int> instantiated?
主要:
Foo f; // f has pi of type Pow<int>. so Pow<int> is instantiated?