문제

Why does the following not compile:

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

What is a way to make it work ?

도움이 되었습니까?

해결책

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

You can not take a pointer to a type. If you want to copy object t to data, do it like this :

template <typename T>
  bool loadStrategyRequestType(T t)
  {
    data = malloc(sizeof(T));
    memcpy ( data, &t, sizeof(T) );
    return true;
  }

The above may work ok, but it still may do copying when creating objects. Since, the object is not changed, this would be better in order to be sure no object is copied :

template <typename T>
  bool loadStrategyRequestType(const T& t)
  {
    data = malloc(sizeof(T));
    memcpy ( data, &t, sizeof(T) );
    return true;
  }

As I mentioned in comments, when implementing function templates, if c++11 is available, it is best to use universal reference. Why? Because they cover every possible case.

template <typename T>
  bool loadStrategyRequestType(T&& t)
  {
    data = malloc(sizeof(T));
    memcpy ( data, &t, sizeof(T) );
    return true;
  }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top