Pregunta

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 ?

¿Fue útil?

Solución

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;
  }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top