0

In my cpp file, before every function I need to include the line:

template <typename T>

Is there some short hand notation so that, instead of typing this before every function, I can type the statement just once for a group of functions ?

Also, I need to include <T> after the class name, for example:

void MyClassName<T>::setDefaultValues()

Is there some way I can group all the template functions so I don't have to repeatedly type this for each function ?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Rahul Iyer
  • 19,924
  • 21
  • 96
  • 190
  • 2
    That syntax enables you to express your intentions. In the latest standard I think that certain function templates can be expressed in a more concise form like `void f(auto x){...}` – MatG Mar 05 '22 at 06:59
  • 2
    Not directly related to your question, but generally putting all the implementations of template functions in `cpp` files is not a good design choice. Templates should generally be implemented in a header file. – super Mar 05 '22 at 08:16
  • You have separated your class method declarations from your class method definitions. For template classes, this separation can be [quite tricky](https://stackoverflow.com/questions/495021/). As such, in your case, every definition must state that it belongs to a template class, there is no avoiding that. Your only other option is to implement the methods inline instead in the class declaration instead. That will avoid both issues. – Remy Lebeau Mar 05 '22 at 18:36
  • @RemyLebeau Yes I moved everything to the class declaration. I read another article which said in some cases you can separate the two so was experimenting with that. – Rahul Iyer Mar 06 '22 at 05:21

2 Answers2

4

Nope. If you need it for each function, then the compiler needs to be told this directly before each function.

A slightly shorter way is of course template <class T>

And we could get even shorter if we resort to macros.

Elliott
  • 2,603
  • 2
  • 18
  • 35
1

Since this is a templated type, and you are on C++11, the consuming types are going to need the full definition anyway which means your other files will be #include ""-ing your source file.

Why not define everything in the header file like STL does for its containers and save you the trouble of redundant tokens and callers having to include files they don't really need to. Don't split the template into definition and implementation.

Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32