C++ 用C+消除重复+;模板
我想您可以使用宏:C++ 用C+消除重复+;模板,c++,templates,dry,C++,Templates,Dry,我想您可以使用宏: #include "ArrayList.h" // do some magic ArrayList(): innerArray(new T[0]), len(0) { // constructor stuff } ~ArrayList() { // destructor stuff } \define\u ARRAYLIST\u模板(F,…)模板\ A::F(uu VA_ARGS_uuu) 使用它可以执行以下操作: #define DEFINE_ARRA
#include "ArrayList.h"
// do some magic
ArrayList(): innerArray(new T[0]), len(0) {
// constructor stuff
}
~ArrayList() {
// destructor stuff
}
\define\u ARRAYLIST\u模板(F,…)模板\
A::F(uu VA_ARGS_uuu)
使用它可以执行以下操作:
#define DEFINE_ARRAYLIST_TEMPLATE(F, ...) template <typename T> \
A<T>::F(__VA_ARGS__)
DEFINE_ARRAYLIST_模板(ARRAYLIST):innerArray(nullptr),len(0)
//^^^^^^^<我先前的建议
{}
DEFINE_ARRAYLIST_模板(ARRAYLIST,int n):innerArray(新的T[n]),len(n)
{}
定义_ARRAYLIST_模板(~ARRAYLIST)
{}
您知道无论如何都需要将实现保留在标题中,对吗?那么为什么不在类中定义它们呢?我不认为这是在重复你自己…@LuchianGrigore等等,实现不是在.cpp
和标题中的定义中吗?而且,innerArray(新的t[0])
是不对的。改为innerray(nullptr)
。@Downvoter请解释您的downvote,我将很乐意改进这个答案。
#define DEFINE_ARRAYLIST_TEMPLATE(F, ...) template <typename T> \
A<T>::F(__VA_ARGS__)
DEFINE_ARRAYLIST_TEMPLATE(ArrayList) : innerArray(nullptr), len(0)
// ^^^^^^^ < my earlier suggestion
{}
DEFINE_ARRAYLIST_TEMPLATE(ArrayList, int n) : innerArray(new T[n]), len(n)
{}
DEFINE_ARRAYLIST_TEMPLATE(~ARRAYLIST)
{}