将模板指针传递给 memcpy
Passing a Template pointer to memcpy
为什么以下内容不编译:
struct Carrier
{
void* data;
int StrategyRequestType;
Carrier(int StrategyRequestType )
{
StrategyRequestType = StrategyRequestType;
}
template <typename T>
bool loadStrategyRequestType(T)
{
data = malloc(sizeof(T));
memcpy ( data, &T, sizeof(T) ); // Syntax error here - "expected primary expression before ',' token"
return true;
}
};
有什么方法可以使其工作?
template <typename T>
bool loadStrategyRequestType(T)
{
data = malloc(sizeof(T));
memcpy ( data, &T, sizeof(T) ); // Syntax error here - "expected primary expression before ',' token"
return true;
}
不能使用指向类型的指针。如果要将对象 t 复制到数据,请像这样操作:
template <typename T>
bool loadStrategyRequestType(T t)
{
data = malloc(sizeof(T));
memcpy ( data, &t, sizeof(T) );
return true;
}
上述方法可能工作正常,但在创建对象时仍然可以进行复制。由于对象没有更改,因此最好确保没有复制任何对象:
template <typename T>
bool loadStrategyRequestType(const T& t)
{
data = malloc(sizeof(T));
memcpy ( data, &t, sizeof(T) );
return true;
}
正如我在注释中提到的,在实现函数模板时,如果 c++11 可用,最好使用通用引用。为什么?因为它们涵盖了所有可能的情况。
template <typename T>
bool loadStrategyRequestType(T&& t)
{
data = malloc(sizeof(T));
memcpy ( data, &t, sizeof(T) );
return true;
}
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 从向量到空指针的 memcpy(反之亦然)不起作用
- 由于指针算法错误,代码在 memcpy 中崩溃
- memcpy是否取决于源指针和目标指针的类型
- 使用 aligned_malloc 和 memcpy 多次将结构复制到指针
- memcpy指向炭缓冲区的指针
- 可以使用memcpy()来复制包含指针的结构吗
- Memcpy崩溃,具体取决于指针类型
- 用memcpy c 读取并写入指针功能
- 我可以对我之前新建的指针使用 memcpy 吗?
- 使用memcpy将数据复制到结构的成员,并给出指向结构的双指针
- 使用Memcpy扩展指针数组的大小
- Memcpy字符指针
- 如何获得指向memcpy成员变量的指针
- 使用 'memcpy()' 为指针分配地址
- 将模板指针传递给 memcpy
- 可以删除使用memcpy()复制的类指针吗?