typedef和显式实例化之间的代码重复
Code duplication between typedefs and explicit instantiations
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>, '*'>;
// ...
正如您所看到的,头文件中的typedef和实现文件中的显式类模板实例化之间存在一些代码重复。是否有一些方法可以消除重复,而不需要像往常一样将"所有内容"放在头文件中?
这是无效的,并且被实现拒绝,因为在详细的类型说明符中使用了typedef名称
template class addition;
以下内容也是无效的,因为标准规定在详细说明的类型说明符中必须包含一个简单的模板id。不过,Comeau在线和GCC都接受这一点。
template class addition::binary_operation;
你可以应用一个变态的变通方法,尽管是完全符合标准的
template<typename T> using alias = T;
template class alias<multiplication>::binary_operation;
至少我在快速浏览规范时不会发现它是无效的。
使用宏。你可以写一个类似的标题
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"
我问自己,为什么你真的要写一个.cpp文件,因为你有模板,它们要么全部放在头文件中,要么放在一个seprarate文件中,例如".icc",它保存了cpp文件中的内容。我不确定,但tempalates的定义不应该总是在一个编译单元中。
请参阅->在.CPP文件中存储C++模板函数定义
相关文章:
- 在c代码之间共享数据的最佳方式
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 当我使用按引用返回时,我不知道这些代码之间的区别
- 如何在括号与代码之间添加空格以进行C++?
- 这两个代码之间的差异(为什么我的数组也有额外的空间,即使我限制了它)
- 无法将Android WebView渲染到C 和Java代码之间共享的外部纹理中
- 这些代码之间的区别在哪里?输出不应该是一样的吗?
- Objective-C源代码和clang -rewrite-objc C++代码之间有什么关系?
- 框架代码和普通代码之间的区别
- FFMPEG生成的零散的MP4文件和代码之间的不同之处在于
- 我不知道为什么只有一个代码在两个代码之间具有sigsegv(看起来相同)
- 为什么这两个代码之间的运行时间差异这么长
- C# 和 C++ 代码之间的链接在 64 位计算机中不起作用
- 在C++和Fortran代码之间传递复数数组
- 在C++和 Python 代码之间转移控制权
- 在托管代码和非托管代码之间传递非托管结构的安全数组
- 自定义Direct2D呈现托管代码和非托管代码之间的批封送处理
- 是否有Visual c++编译器在线,以及如何在c++和vs简单代码之间转换
- 在我的c++代码之间向matlab传递一个字符串变量
- 这些C++代码之间有什么区别