Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing non-template parts of templated class in cpp

Tags:

c++

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;
}
like image 511
lennartVH01 Avatar asked Nov 01 '25 13:11

lennartVH01


1 Answers

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.

like image 128
lubgr Avatar answered Nov 03 '25 04:11

lubgr