2012-07-10 108 views
4

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>, '*'>; 
// ... 

正如你所看到的,有在头文件和明确的类型定义之间的一些代码重复实现文件中的类模板实例化。有没有办法摆脱不需要像往常一样将“一切”放在头文件中的重复?

+0

我认为你不能在.cpp文件中写'template class addition;',这是一种耻辱。 – 2012-07-10 13:54:11

+0

nope :('错误:在'class''后面使用typedef-name'addition' – fredoverflow 2012-07-10 13:55:41

+0

我在assuning decltype也无济于事......但C++仍然有旧的预处理器......你可以用宏通用部分:-) – 2012-07-10 17:38:56

回答

1

这是因为一个typedef实现无效并驳回名称用于e laborated类型说明符

template class addition; 

下是无效的也是如此,因为标准说必须有包含在精细的类型说明一个简单的模板ID。但是,Comeau在线和GCC都接受它。

template class addition::binary_operation; 

你可以申请一个变态的解决办法,虽然是完全符合标准

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

至少我无法找到它在快速浏览过该规范是无效的了。

0

我问我自己,为什么你实际上写了一个.cpp文件,因为你有模板,他们应该去所有的头文件或一个seprarate文件,例如“.icc”,它包含cpp的东西文件。我不确定,但tempalates定义应始终不在编译单位。

请参阅 - >Storing C++ template function definitions in a .CPP file

2

使用宏。你可以写一个头像

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

然后,你可以做

#define I_HATE_MACROS(a, b) typedef a b; 

或者

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

然后

#include "DisgustingMacroHackery.h" 
+0

快速提示:由于I_HATE_MACROS中第一个参数的逗号,因此它不会按原样运行。为了使其工作,它需要与http://stackoverflow.com/a/13842612/543913类似 – dshin 2014-04-22 21:42:27