模板错误

bre*_*ett 3 c++ templates

我听说C++模板在使用之前不会产生错误.这是真的吗?有人可以解释我们是如何工作的吗?

Chu*_*dad 6

模板遵循两阶段编译模型.

struct X{
private:
   void f(){}
};

template<class T> void f(T t){
   int;   // gives error in phase 1 (even if f(x) call is commented in main)
   t.f(); // gives error only when instantiated with T = X, as x.f() is private, in phase 2
}

int main(){
   X x;
   f(x);
}
Run Code Online (Sandbox Code Playgroud)