一开始先要区分两种意义,一种是C++ 标准所谓的“scope of the templatedefinition”,直译就是“定义模板的范围”。另一种是C++标准所谓的“scope of the temlate instantiation”,可以直译为“实例化模板的范围”。
第一种情况
extern char foo(char);
template <class type>
class ScopeRules
{
public:
void invariant(){ _member = foo(_val); } //由于_val为已知类型,因此可以使用当前范围的(定义模板范围)char foo(char)函数来决议invariant()该调用哪个版本的foo函数,不必等待实例化来判断
type type_dependent(){ return foo(_member); } //由于_member与模板参数type类型有关,因此需要推迟到实例化的时候调用实例化模板范围的int foo(int)函数
private:
int _val;
type _member;
};
第二种情况
extern int foo(int);
ScopeRules< int > sr;
sr.invariant();
sr.type_dependent();
深度探索C++对象模型的解释如下:
template 之中, 对于一个非成员名字的决议结果是根据这个 name的使用是否与“用以实例化该模板的参数类型”有关来决定name。如果其使用互不相干,那么就以“scope of the template dclaration”来决定name。如果其使用的互相关联,那么就以“scope of the templateinstantiation”来决定name.