Is there a cleaner way to write template function definitions?

Viewed 70

A basic template class might look something like this:

Example.h

template<class T> 
class Example {
public:
    T doSomething();
};

Example.cpp

#include "Example.h"

template<class T>
T Example<T>::doSomething() {
    // ...
    return  0;
}

In a class this small, this is fine, but when dealing with larger classes, potentially with more template args, it can become annoying to have to retype template<class T, ...> and Example<T, ...> constantly, and if the template args change, you have to change it everywhere. Putting the aforementioned code in two preprocessor defines seems to work fine, but looks really messy:

Example.cpp

#include "Example.h"

#define Tmpl template<class T>
#define Example Example<T>

Tmpl 
T Example::doSomething() {
    // ...
    return 0;
}

Is there a slightly cleaner way of doing this, or is #define the only way I have?

1 Answers

By the sounds of it, the best option is just to write out everything in full. Unfortunate, but I suppose this is what find/replace is for. Additionally, the code in my question would give linker errors when used in context, unless function definitions were given in the header, or (I think) if template instances were explicitly written in the source file (Why can templates only be implemented in the header file?).

Related