本文介绍了模板如何实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 C ++ Primer 5th Edition 的练习:

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)
}

以下是我尝试过的内容:

Below is what I tried:

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

(a) Stack<char> is instantiated , but no member of it is instantiated.

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

(b) Stack<double> is instantiated , but no member of it is instantiated.

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

(c) Stack<int> and its default constructor are instantiated.

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

(d) (e) totally no idea...

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

(f) Stack< string > is instantiated , but no member of it is instantiated.

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

Am I right? Can anyone tell me how this code is instantiated?

推荐答案

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

In your specific case a declaration doesn't mean an instantiation

#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!!

}

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

notice the pointer/reference stuff: they don't require instantiation since no data is actually allocated (a pointer is just a few bytes to contain the address, has no need to have all the data stored.. take a look at the pimpl idiom ).

仅当分配了东西时,才必须完全解析模板(而且这种情况发生在编译时,这就是为什么它们通常都需要声明和定义的原因.尚无链接阶段)

Only when stuff is allocated then the template has to be completely resolved (and that happens at compile-time, that's why they usually need both declaration and definition.. there's no linking phase yet)

这篇关于模板如何实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 08:09