模板是如何实例化的?

Yue*_*ang 17 c++ templates instantiation

这是C++ Primer第5版的练习:

练习16.27:对于每个带标签的语句,解释实例化发生的情况(如果有的话).如果模板被实例化,请解释原因; 如果没有,请解释原因.P.677

template <typename T> class Stack { };

void f1(Stack<char>);                   // (a)

class Exercise {
    Stack<double> &rsd;                 // (b)
    Stack<int>    si;                   // (c)
};

int main() {
    Stack<char> *sc;                    // (d)
    f1(*sc);                            // (e)
    int iObj = sizeof(Stack< string >); // (f)
}
Run Code Online (Sandbox Code Playgroud)

以下是我的尝试:

(a)Stack<char>被实例化,但没有实例化它的成员.

(b)Stack<double>被实例化,但没有实例化其成员.

(c)Stack<int>并实例化其默认构造函数.

(d)(e)完全不知道......

(f)Stack< string >被实例化,但没有实例化其成员.

我对吗?谁能告诉我这个代码是如何实例化的?

Mar*_* A. 11

在您的具体情况下,声明并不意味着实例化

#include <iostream>
using namespace std;


template <typename T> class Stack {
  typedef typename T::ThisDoesntExist StaticAssert; // T::NotExisting doesn't exist at all!
};


void f1(Stack<char>); // No instantiation, compiles

class Exercise {
  Stack<double> &rsd; // No instantiation, compiles (references don't need instantiation, are similar to pointers in this)

  Stack<int>    si; // Instantiation! Doesn't compile!!
};


int main(){

  Stack<char> *sc; // No Instantiation, this compiles successfully since a pointer doesn't need instantiation

  f1(*sc); // Instantiation of Stack<char>! Doesn't compile!!

  int iObj = sizeof(Stack< std::string >); // Instantiation of Stack<std::string>, doesn't compile!!

}
Run Code Online (Sandbox Code Playgroud)

注意指针/引用的东西:它们不需要实例化,因为实际上没有分配数据(指针只是包含地址的几个字节,不需要存储所有数据..看看pimpl成语).

只有在分配东西时才必须完全解析模板(这在编译时发生,这就是为什么它们通常需要声明和定义......还没有链接阶段)