在C++中,我们经常遇到需要对一个对象数组进行复制,比如下面一个结构:
struct STest
{
int a;
int b;
vector vctInt;
};
我们定义了两个数组:
STest A[20];
STest B[20];
需要将数组A中的所有内容复制到B数组中,通常我们的做法都是这样:
for(size_t i = 0; i < ARRAYSIZE(A); ++i)
{
A[i] = B[i];
}
这里不能直接使用memcpy,因为STest中有vector类型。但是,如果我们定义的是内置类型的数组,则上面的代码效率较低,而直接使用memcpy会更高效。
为了解决上面的问题,我们可以使用C++模板对不同的类型进行不同的处理。下面有两种写法:
第一种写法是最容易想到的,就是直接写一个模板,并对这个模板的C++内置类型进行特化处理:
template
inline void ArrayAssign(T (&A)[N], T (&B)[N])
{
for(size_t i = 0; i < N; ++i)
A[i] = B[i];
}
template
inline void ArrayAssign(bool (&A)[N], bool (&B)[N])
{
memcpy(A,B,sizeof(A));
}
template
inline void ArrayAssign(char (&A)[N], char (&B)[N])
{
memcpy(A,B,sizeof(A));
}
template
inline void ArrayAssign(short (&A)[N], short (&B)[N])
{
memcpy(A,B,sizeof(A));
}
template
inline void ArrayAssign(int (&A)[N], int (&B)[N])
{
memcpy(A,B,sizeof(A));
}
template
inline void ArrayAssign(long long (&A)[N], long long (&B)[N])
{
memcpy(A,B,sizeof(A));
}
template
inline void ArrayAssign(unsigned char (&A)[N], unsigned char (&B)[N])
{
memcpy(A,B,sizeof(A));
}
template
inline void ArrayAssign(unsigned short (&A)[N], unsigned short (&B)[N])
{
memcpy(A,B,sizeof(A));
}
template
inline void ArrayAssign(unsigned int (&A)[N], unsigned int (&B)[N])
{
memcpy(A,B,sizeof(A));
}
template
inline void ArrayAssign(unsigned long long (&A)[N],unsigned long long (&B)[N])
{
memcpy(A,B,sizeof(A));
}
下面是第二种写法,这种写法,把内置类型的判断提出来,可以方便其它地方使用:
template
struct _if{};
template
struct _if{ typedef B Type; };
template
struct _if{ typedef C Type; };
template
inline size_t ARRAYSIZE(T (&)[N])
{
return N;
}
template
struct IsInnerType { static const bool Value = false; };
template<>
struct IsInnerType { static const bool Value = true; };
template<>
struct IsInnerType { static const bool Value = true; };
template<>
struct IsInnerType { static const bool Value = true; };
template<>
struct IsInnerType { static const bool Value = true; };
template<>
struct IsInnerType { static const bool Value = true; };
template<>
struct IsInnerType { static const bool Value = true; };
template<>
struct IsInnerType { static const bool Value = true; };
template<>
struct IsInnerType { static const bool Value = true; };
template<>
struct IsInnerType { static const bool Value = true; };
template
struct ArrayAssignInnerType
{
static inline void Invoke(T (&A)[N], T (&B)[N])
{
memcpy(A,B,sizeof(A));
}
};
template
struct ArrayAssignCustomType
{
static inline void Invoke(T (&A)[N], T (&B)[N])
{
for(size_t i = 0; i < N; ++i)
A[i] = B[i];
}
};
template
inline void ArrayAssign(T (&A)[N], T (&B)[N])
{
_if::Value,ArrayAssignInnerType,ArrayAssignCustomType >::Type::Invoke(A,B);
}
经过上面的处理,我们可以不用担心效率问题;同时,写起来也方便很多,而且不会出错。直接按如下写就OK了:
ArrayAssign(B,A);
以上代码在VC和GCC下编译通过。