Code duplication between typedefs and explicit instances

tree.h

template<typename Functor, char Operator> class binary_operation : public node { // ... unimportant details ... unsigned evaluate() const; void print(std::ostream& os) const; }; typedef binary_operation<std::plus<unsigned>, '+'> addition; typedef binary_operation<std::multiplies<unsigned>, '*'> multiplication; // ... 

tree.cpp

 template<typename Functor, char Operator> unsigned binary_operation<Functor, Operator>::evaluate() const { // ... unimportant details ... } template<typename Functor, char Operator> void binary_operation<Functor, Operator>::print(std::ostream& os) const { // ... unimportant details ... } template class binary_operation<std::plus<unsigned>, '+'>; template class binary_operation<std::multiplies<unsigned>, '*'>; // ... 

As you can see, there is code duplication between typedefs in the header file and an explicit instance of the template instance in the implementation file. Is there a way to get rid of duplication that does not require putting "everything" in the header file, as usual?

+4
source share
3 answers

This is unacceptable and is rejected by implementations because the typedef name is used in the specified type specifier

 template class addition; 

The following is also unacceptable: the standard says that there should be a simple template identifier contained in the specified type specifier. Couto Online and GCC both agree on this.

 template class addition::binary_operation; 

You can use a workaround, but fully standards compliant

 template<typename T> using alias = T; template class alias<multiplication>::binary_operation; 

At least I could not find it unacceptable, quickly looking at the specification.

+1
source

Use a macro. You can write a title, for example

 I_HATE_MACROS(binary_operation<std::plus<unsigned>, '+'>, addition) I_HATE_MACROS(binary_operation<std::multiplies<unsigned>, '*'>, multiplication) 

Then you can do

 #define I_HATE_MACROS(a, b) typedef ab; 

or

 #define I_HATE_MACROS(a, b) template class a; 

Then

 #include "DisgustingMacroHackery.h" 
+2
source

I ask myself: why are you actually writing a .cpp file, since you have templates, and they should go either in the header file or in a separate file, for example ".icc", which contains the material from the cpp file, I'm not sure , but tempalates definitions should NOT always be in a compilation unit.

See → Saving C ++ Template Function Definitions in a .CPP File

0
source

All Articles