Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one avoid duplicating class template specification for each member function?

Tags:

c++

templates

If I have a template class specification like so,

template <typename T>
class MyClass {
public:
    void fun1();
    // ...
    void funN();
};

template <typename T>
void MyClass<T>::fun1() {
    // definition
}

// ...

template <typename T>
void MyClass<T>::funN() {
    // definition
}

If I change the class template to something else, say I add an extra parameter:

template <typename T, typename U>
class MyClass {
    // ...
};

Then I have to change each function definition (fun1, ..., funN) to agree with the class template specification:

template <typename T, typename U>
void MyClass<T,U>::fun1() { //... }

Are there any strategies for avoiding this? Could I use macros e.g.

#define DFLT_TEMPLATE template<typename T, typename U>
#define DFLT_CLASS  class<T,U>

DFLT_TEMPLATE
void DFLT_CLASS::fun1() { // ... }

Or is this considered bad practice?

like image 506
richardr Avatar asked Nov 16 '10 14:11

richardr


4 Answers

To me, the benefits of using a macro here are far overshadowed by the drawbacks. Yes, if you use a macro then if you ever need to add an additional template parameter, you'll only need to make a single modification. But anyone else reading your code is probably going to vomit.

I mean, are you going to do this for every template you have? Your code will become infested with ugly macros.

like image 68
Charles Salvia Avatar answered Sep 28 '22 08:09

Charles Salvia


How many member functions do you have that this is an issue?

I think either they are small enough to be defined within the class template or the adaption of their algorithms to an additional template parameter would by far outweigh the replacement of those function headers.

Also, your editor ought to do this for you in no time anyway.

like image 26
sbi Avatar answered Sep 28 '22 10:09

sbi


yes you could but don't forget to use "#undef DFLT_TEMPLATE" and "#undef DFLT_CLASS" at the end of file to avoid compiler warnings if your project have several templates with same macros definitions

like image 37
pboulanger Avatar answered Sep 28 '22 10:09

pboulanger


Inheritation is better than macro.

If you want to change only a few functions and variables, make the specialized class inherit a common class that provides common functions/variables.

like image 40
peoro Avatar answered Sep 28 '22 09:09

peoro