Ale*_*Dan 5 c++ templates class
我想知道当我通过指定模板类型参数创建类模板的实例时.
1)为什么非被调用的函数没有得到实例化?.
2)在我尝试使用之前,他们不会被编译?
3)这种行为背后的逻辑是什么?
例
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();
}
Run Code Online (Sandbox Code Playgroud)
如果他们实例化整个类,那么您可能会得到无效代码。
你并不总是想要这样。
为什么?因为在 C++ 中,很难(据我所知,在某些情况下,完全不可能)说“仅当 X、Y 和 Z 为真时才编译此代码”。
例如,你会怎么说“如果嵌入对象可以复制,则只有我的复制构造函数”?据我所知,你不能。
所以他们只是让它们无法编译,除非你实际调用它们。
| 归档时间: |
|
| 查看次数: |
232 次 |
| 最近记录: |