为什么不实例化模板类成员? [英] Why uncalled template class members aren't instantiated?

查看:127
本文介绍了为什么不实例化模板类成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道当我创建一个类模板的实例并指定模板类型参数。

1)为什么不调用函数不被调用? 。

2)不会编译,直到我尝试使用它?

3)什么是逻辑背后这种行为?

I was wondering that when I create an instance of a class template with specifying the template type parameter.
1) why the non-called function do not get instatiated ? .
2) dont they get compiled until I try to use it ?
3) what is the logic behind this behavior ?

示例

template <class T>
class cat{
public:

T a;
void show(){
   cout << a[0];
}
void hello(){
   cout << "hello() get called \n";
}
}; 

int main(){
cat<int> ob1; // I know that show() did not get instatiated, otherwise I will get an    error since a is an int
ob1.hello();

 }


推荐答案

为什么?因为在C ++中,它是(在某些情况下,完全不可能,就我所知)说,只有编译这个代码,如果X,Y和Z是真的。

Why? Because in C++, it's difficult (and in some cases, outright impossible, as far as I know) to say, "only compile this code if X, Y, and Z are true".

例如,你怎么说,只有我的复制构造函数如果嵌入对象可以复制?据我所知,你不能。

For example, how would you say, "only my copy constructor if the embedded object can be copied"? As far as I know, you can't.

所以他们只是使他们不编译,除非你实际调用他们。

So they just made them not compile unless you actually call them.

这篇关于为什么不实例化模板类成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆