类模板实例化

Alc*_*ott 14 c++ templates instantiation

我刚刚阅读了有关CRTP的wiki文章,我对模板实例化有点困惑.

根据维基,

成员函数体(定义)直到它们的声明后很久才被实例化.

我不太明白这意味着什么.

假设我有一个类模板:

template <typename T>
class A
{
    public:
        void foo(T t)
        {
            //...
        };
};
Run Code Online (Sandbox Code Playgroud)

当我实例化类模板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?
}
Run Code Online (Sandbox Code Playgroud)

Kos*_*Kos 13

你好像混淆了一件事:

实例化在编译期间发生,而不是在运行时期间发生.因此,您不能说"在哪一行"实例化类模板或函数模板.

也就是说,你对成员函数模板没有与类模板一起实例化是正确的.

你可以在这种情况下观察它:你有以下文件

  • template.h(定义类A和函数A :: foo)
  • a.cpp(使用A)
  • b.cpp(使用A和A :: foo)

然后在编译a.cpp期间,只会实例化A.但是,在编译b.cpp期间,两者都将被实例化.

因此,如果A :: foo包含一组给定模板参数的语义无效代码,您将在b.cpp中获得编译错误,但不会在a.cpp中获得编译错误.

我希望能搞清楚!


Seb*_*ach 9

对于类模板,经验法则是只实例化那些实际使用的成员.

如果你想要完整的实例化,C++提供了显式的实例化(但是,通常你没有;事实上并非每个位都被完全实例化意味着你的模板类更通用,因为它降低了要求T,请注意语法检查和查找非依赖类型(不依赖的东西T)仍然发生).

您将在此处找到更完整的答案:GCC和MS编译器的模板实例化详细信息