类模板实例化 [英] class template instantiation
问题描述
我刚读了关于 CRTP 的wiki文章,我对模板实例化有点困惑。
I just read the wiki article about CRTP, and I'm a little confused about template instantiation.
根据wiki,
成员函数体(定义)
。
member function bodies (definitions) are not instantiated until long after their declarations.
我不太明白这是什么意思。
I don't quite understand what it means.
假设我有一个类模板:
template <typename T>
class A
{
public:
void foo(T t)
{
//...
};
};
当我实例化类模板A时,是否实例化成员函数foo()?
When I instantiate the class template A, does it instantiate the member function foo()?
例如:
//in .cpp file
int main()
{
A<int> a; //question 1
//class template is instantiated here, isn't it?
//What about foo(), is it instantiated too?
a.foo(10); //question 2
//according to the quotation, foo() will not be instantiated until it is used.
//if so, foo() is instantiated right here, not in question 1, right?
}
推荐答案
事情:
实例化在编译期间发生,而不是在运行时。因此,你不能说在哪一行上类模板或函数模板被实例化。
Instantiation happens during compilation, not during runtime. Hence you can't say "on which line" a class template or a function template was instantiated.
也就是说,对于成员函数模板不能与类模板一起实例化,这是正确的。
That said, you're right about the fact that member function templates aren't instantiated together with class templates.
您可以在这种情况下观察它:
You could observe it in such a case: You have the following files
- template.h(定义类A和函数A: :foo)
- a.cpp(使用A)
- b.cpp(使用A和A :: foo)
然后在编译a.cpp的过程中,只有A被实例化。但是,在b.cpp的编译过程中,两者都将被实例化。
Then during compilation of a.cpp, only A would be instantiated. However, during compilation of b.cpp, both would be instantiated.
因为这一点,如果A :: foo包含给定模板集合的一些语义无效的代码参数,你会得到b.cpp中的编译错误,但不会a.cpp。
Because of this, in case A::foo contained some semantically invalid code for a given set of template parameters, you would get compile errors in b.cpp, but not a.cpp.
我希望清除的东西!
这篇关于类模板实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!