0

Consider the method below:

template <class T>
void Entry<T>::setValue(T * value) {
  int size = ?;
  this->key = new T();
  memcpy(this->value, value, size);
}

How I could find the length for value? If it was a char* i could use something like that: strlen(value), but it is not. What the alternstive here?

I try use this:

template <class T>
void Entry<T>::setValue(T * value) {
  this->value = value;
}

but the value was staying empty after the method call.

UPDATE

I have tried this, but do not compile:

template <class T>
void Entry<T>::setValue(T * value) {
  int size = sizeof(value)/sizeof(value[0]);
  cout << "size = " << size << endl;
  this->key = new T();
  memcpy(this->value, value, size);
}

the error is:

Entry.cpp:35:13: error: cannot convert ‘JSON_Value*’ to ‘char*’ in assignment
   this->key = new T()

UPDATE 2

Another try, this time the code compiles but the execution gives me a Segmentation fault in the second line:

template <class T>
void Entry<T>::setValue(T * value) {
  T temp = *value;
  *value = *this->value;
  *this->value = temp;
}
Kleber Mota
  • 8,521
  • 31
  • 94
  • 188
  • `sizeof(T)` but it seems you are after something else, given your comment about `strlen`, which does *not* give the size of a `char*`. – juanchopanza Sep 04 '17 at 13:50
  • By size do you mean length, or size in bytes? Since you are using `memcpy`, I would believe you need the `sizeof` operator – Arnav Borborah Sep 04 '17 at 13:54
  • more like length, I mean. `sizeof` do not return what I want ( I already try that). – Kleber Mota Sep 04 '17 at 13:58
  • @juanchopanza the answer to the other question you suggested do not solve the current problem (see the update I added). – Kleber Mota Sep 04 '17 at 14:07
  • It tells you why what you're trying can't possibly work. – juanchopanza Sep 04 '17 at 14:08
  • What the alternative then? How I could assign a value to a member of a template class? – Kleber Mota Sep 04 '17 at 14:11
  • You cannot get lenght of dynamically allocated array just from pointer. Btw, sizeof(value)/sizeof(value[0]) is pretty much random value as sizeof(value) will evaluate to 4 or 8 (on 32 or 64 bit system) and sizeof(value[0]) into sizeof(T) – R2RT Sep 04 '17 at 14:11
  • @R2RT Is there a way to assign a value to the member variable of a template class in that particular case? This class have another attribute, but as its type was `char* ` was easy figure out how to do this assignment. – Kleber Mota Sep 04 '17 at 14:13
  • Something like this? This is basic example, it would be better to make some more template magic with static_assert and type traits. https://repl.it/KgF0/0 – R2RT Sep 04 '17 at 14:21

0 Answers0