Home > Enterprise >  How template class resolve member methods
How template class resolve member methods

Time:10-17

I used to do what suggested here https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl to separate template header and implementations. We basically explicitly instantiate the desired template at the end of .cc file so that the compilation unit contains enough information for the linker to work with.

I recently learnt that we only need to explicitly instantiate a class constructor to be able to create an instance. For example,

// .h file
template<typename T>
class A {
 public:
  A(T& t) : t_(t) {};
  
  void PublicMethod();
 private:
  void PrivateMethod();
  T& t_;
};

// .cc file
template<typename T>
void A<T>::PublicMethod() { PrivateMethod; return;}

template<typename T>
void A<T>::PrivateMethod() { 
 // Do some work.
 return;
}
// Here I only instantiate the constructor and public interface.
template A::A(int);
template void A<int>::PublicMethod();

// In main, I can do following.
int main() {
 A<int> a(2);
 a.PublicMethod();
}

The part I am not clear is:

  1. if I instantiate the public method, does it automatically instantiate all relevant private methods as well automatically?

CodePudding user response:

No, if you explicitly instantiate a member (including a constructor), then only the definition for that member will be explicitly instantiated.

The explicit instantiation may cause implicit instantiation of other members of the class, but that isn't enough to use these members in a different translation unit. If you do not intent to use the private members in a different translation unit though, then it would be sufficient to explicitly instantiate the public/protected member functions.

If you want to explicitly instantiate all class members, you should explicitly instantiate the class template specialization itself:

template class A<int>;

template A::A(int);

This is not correct. Your constructor expects a reference, so it should be int& instead of int. Furthermore A is the template, not a specialization of it. You must specify a specialization:

template A<int>::A(int);
  • Related