这是一个练习,来自C++ 入门第五版:
练习 16.27:对于每个带标签的语句,解释什么(如果有)
实例化发生。如果实例化了模板,请解释原因;如果
不,请解释为什么不。第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)
}
以下是我尝试过的:
(a) Stack<char>
被实例化,但它的任何成员都没有被实例化。
(b) Stack<double>
被实例化,但它的任何成员都没有被实例化。
(c) Stack<int>
及其默认构造函数被实例化。
(d) (e) 完全不知道...
(f) Stack< string >
被实例化,但它的任何成员都没有被实例化。
我对吗?谁能告诉我这段代码是如何实例化的?
在您的具体情况下,声明并不意味着实例化
#include <iostream>
using namespace std;
template <typename T> class Stack {
typedef typename T::ThisDoesntExist StaticAssert; // T::ThisDoesntExist 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!!
}
注意指针/引用的东西:它们不需要实例化,因为实际上没有分配数据(指针只是几个字节来包含地址,不需要存储所有数据..看看粉刺成语 http://en.wikipedia.org/wiki/Opaque_pointer ).
仅当物品被分配时那么模板必须完全解析(这发生在编译时,这就是为什么它们通常需要声明和定义......还没有链接阶段)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)