i***h 发帖数: 12655 | 1 在Effective STL 书里看到的, 但是不太清楚.
为什么在第二段code里可以直接用DeleteObject,
而第一个里面一定要DeleteObject呢?
第一段Code:
template
struct DeleteObject:
public unary_function {
void operator()(const T* ptr) const
delete ptr;
}
};
void doSomething()
{
for_each(vwp.begin(), vwp.end(), DeleteObject);
}
第二段Code:
struct DeleteObject { // templatization and base
// class removed here
template II templatization added here
void operator()(const T* ptr) const
{
delete ptr;
}
} |
X****r 发帖数: 3557 | 2 因为第一段里面DeleteObject是class template,不能直接创建对象,
(你漏了对括号吧)所以必须指定类型参数;
第二段里面DeleteObject是class,所以可以直接创建对象,
这个类有一个member function template,但这个不在这里resolve,
而在for_each的实现里面
【在 i***h 的大作中提到】 : 在Effective STL 书里看到的, 但是不太清楚. : 为什么在第二段code里可以直接用DeleteObject, : 而第一个里面一定要DeleteObject呢? : 第一段Code: : template : struct DeleteObject: : public unary_function { : void operator()(const T* ptr) const : delete ptr; : }
|
i***h 发帖数: 12655 | 3 也就是说function template会在编译时自动寻找best fit instantiation
class template就不行
谢谢
【在 X****r 的大作中提到】 : 因为第一段里面DeleteObject是class template,不能直接创建对象, : (你漏了对括号吧)所以必须指定类型参数; : 第二段里面DeleteObject是class,所以可以直接创建对象, : 这个类有一个member function template,但这个不在这里resolve, : 而在for_each的实现里面
|
X****r 发帖数: 3557 | 4 是我用词不当,instantiation这个词在C++里专用的,我指的是创建对象。
只有类(class)才能用来创建对象,类模板(class template)不能。
【在 i***h 的大作中提到】 : 也就是说function template会在编译时自动寻找best fit instantiation : class template就不行 : 谢谢
|