lennartVH01
lennartVH01

Reputation: 208

Storing non-template parts of templated class in cpp

I've been wondering about this for a while, stackoverflow had a bunch of related, but not quite the same questions, so I'm asking it here.

Is it possible for a templated class to have methods in the cpp that do not depend on this template? Evidently these methods aren't affected by the template, so the compiler should be able to compile them separately.

If not possible, what would be a workaround, if I really, really want to separate this code?

template<typename T>
class MyAwesomeVectorClone{
  size_t size;
  size_t capacity;
  T* data;

  bool doesSizeExceedCapacity(); // non template method, define in cpp?
  void add(T& t){// template method
  }
}
bool MyAwesomeVectorClone::doesSizeExceedCapacity() {
  return size > capacity;
}

Upvotes: 4

Views: 654

Answers (2)

R Sahu
R Sahu

Reputation: 206667

Another solution is to add the function, and any other helper functions, in a namespace that clearly indicates that it contains functions useful for implementing the class template.

namespace MyAwesomeVectorClone_Impl_Details
{
   bool doesSizeExceedCapacity();
}

Those functions can be defined in a .cpp file.

Upvotes: 0

lubgr
lubgr

Reputation: 38295

Is it possible for a templated class to have methods in the cpp that do not depend on this template?

No. A class template is not a specific type, you create a type to which these memeber functions can belong only when instantiating the template. So it's impossible to treat member functions that don't depend on the template type parameter differently from the rest of the class template.

What you can do, however, is extracting the parameter-independent parts out into a separate class or separate free functions. This is the subject of Item 44 in Effective C++ by Scott Meyers ("Factor parameter-independent code out of templates"). He presents a matrix example, where the parameter-independent code is moved into a base class from which the actual class template privately inherits. But composition is fine, too, of course.

Upvotes: 4

Related Questions