我刚刚阅读了关于 CRTP 的 wiki 文章,我对模板实例化有点困惑。
根据维基,
member function bodies (definitions) are not instantiated until long after their declarations.
我不太明白这是什么意思。
假设我有一个类模板:
template <typename T>
class A
{
public:
void foo(T t)
{
//...
};
};
当我实例化类模板A时,它是否实例化了成员函数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?
}
最佳答案
你似乎混淆了一件事:
实例化发生在编译期间,而不是运行时。因此,您不能说“在哪一行”实例化了类模板或函数模板。
也就是说,成员函数模板没有与类模板一起实例化这一事实是正确的。
在这种情况下你可以观察到:你有以下文件
- template.h(定义类 A 和函数 A::foo)
- a.cpp(使用 A)
- b.cpp(使用 A 和 A::foo)
然后在 a.cpp 的编译过程中,只有 A 会被实例化。但是,在编译 b.cpp 期间,两者都会被实例化。
因此,如果 A::foo 对于给定的一组模板参数包含一些语义上无效的代码,您将在 b.cpp 中得到编译错误,而不是在 a.cpp 中。
我希望这能解决问题!
关于c++ - 类模板实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8210914/