将模板指针传递给 memcpy

Passing a Template pointer to memcpy

本文关键字:memcpy 指针      更新时间:2023-10-16

为什么以下内容不编译:

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;
  }