From the previous example I've posted here about when the template
is instantiated?, I got the answer that only when a template is used the compiler instantiates it. But look at this example:
template <typename T>
struct Pow{
T operator()(T const& x){ return x * x; }
};
extern template struct Pow<int>; // explicit instantiation declaration
struct Foo{
Pow<int> pi{};
void fn(Pow<int>);
};
void Foo::fn(Pow<int> pw){
// std::cout << pw(7) << '\n';
}
void bar(Pow<int> pwi){
// std::cout << pwi(10) << '\n';
}
int main(){
Foo f;
}
As you can see I've declared an explicit template instantiation
Pow<int>
but haven't defined it. The program works just fine and doesn't complain about the missing definition ofPow<int>
!In the previous topic I've been answered if I use a template type as a type of parameter for a function definition (not declaration) then the template is instantiated but here as you can see: The member function
Foo::fn(Pow<int>)
and the ordinary function functionbar(Pow<int>)
are defined but the compiler doesn't complain about the definition ofPow<int>
?!!!The program fails to compile if I un-comment the lines in the aforementioned functions. so does it mean that
Pow<int>
is not instantiated when used as function parameter in the function definition and as member data like inFoo::Pow<int> pi{};
?I find it confusing:
void f(Pow<int>); // function declaration: Pow<int> is not instantiated yet. void f2(Pow<int>){} // function definition: Pow<int> instantiated? void f3(pow<int> Pwi){ std::cout << Pwi(10);} // function definition and usage of `Pow<int>`: Pow<int> instantiated?
In main:
Foo f; // f has pi of type Pow<int>. so Pow<int> is instantiated?