memcpy的模板变体出错

error in template variant of memcpy

本文关键字:出错 memcpy      更新时间:2023-10-16

我想写memcpy的模板变体:

template< typename T > 
inline T& MemCopy( T& dest, const T& src )
{
  *( T* )memcpy( &dest, &src, sizeof( src ) ) ;
}

当我尝试在VS2010中编译下一个代码时:

typedef short AMSync[ 4 ] ;
static AMPSync aSync ;
void Init( const AMPSync& sync )
{
   MemCopy( aSync, sync ) ;
}

我得到错误:

'T &MemCopy(T &,const T &)' : template parameter 'T' is ambiguous
          : see declaration of 'MemCopy'
          could be 'const short [4]'
          or       'AMPSync'

如果我使用:

template< typename T1, typename T2 > 
inline T1& MemCopy( T1& dest, const T2& src )
{
   *( T1* )memcpy( &dest, &src, sizeof( src ) ) ;
}

则不存在错误,但在这种情况下,编译器无法检查参数的大小

有没有办法实现这两个目的。

template<typename T1, typename T2> 
T1& MemCopy(T1& dest, const T2& src)
{
   static_assert(sizeof(src) == sizeof(dest));
   return *reinterpret_cast<T1*>(memcpy(&dest, &src, sizeof(src)));
}

template<typename T1, typename T2> 
typename std::enable_if<sizeof(T1) == sizeof(T2), T1&>::type MemCopy(T1& dest, const T2& src)
{
   return *reinterpret_cast<T1*>(memcpy(&dest, &src, sizeof(src)));
}

不过你为什么要这么做?你的例子会更好:

static AMPSync aSync ;
void Init( const AMPSync& sync )
{
    aSync = sync;
}