memcpy的模板变体出错
error in template variant of memcpy
我想写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;
}
相关文章:
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 分段错误当我试图运行程序时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 用pybind11包装C++抽象类时出错
- 为x86而非x64编译时出错
- 从R调用C++函数并对其进行集成时出错
- 这个函数哪里出错了
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 为什么 memcpy seg 出错
- 如果使用memcpy,释放内存时出错
- memcpy的模板变体出错