S
S
Slavka2014-05-08 17:59:43
C++ / C#
Slavka, 2014-05-08 17:59:43

Using typeid in a template class

here is the part of the class with the function in question

template <class W>
class CBuffer
{ private:
   W *arr;
   int len;
   int nowIndex;

   W & operator[](unsigned int i)
   {
  if (i<len) {
    return arr[i];
  }
}

void  getElement(TListBox* LB)
{
if(typeid(arr)==typeid(CWeather*)){

   W tmp;
   LB->Items->Clear();
   for (int i = 0; i <len; i++) {

   if(!(arr[i]==tmp)){
  LB->Items->Add(AnsiString("Температура: ") + arr[i].getsTemperature());
  LB->Items->Add("Давление: " +arr[i].getsPressure());
  LB->Items->Add("Скорость ветра: " + arr[i].getsWindSpeed());
  LB->Items->Add("\Направление ветра: "+arr[i].getsWindDirection());
  LB->Items->Add("---------------------------");
   }
   }
   }

   if (typeid(arr)==typeid(short*))
  {
    LB->Items->Clear();
    for (int i = 0; i <len; i++) {
      LB->Items->Add(arr[i]);
    }
   }
}

in the program itself:
CBuffer<CWeather> *buf = new CBuffer<CWeather>();
CBuffer<short> *buf2  = new CBuffer<short>();

so the program does not compile, complains about type mismatch, I don’t know why it gets into both ifs at once, i.e. it either takes the value of CWeather then complains about the output LB->Items->Add(arr[i]); and vice versa

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
jcmvbkbc, 2014-05-08
@jcmvbkbc

typeid of the template class

Bumblebee crab.
What's stopping you from knowing? Are you good at reading error messages?

K
kosmos89, 2014-05-08
@kosmos89

First, as already mentioned, in this case, specialization should be used.
And secondly, there is such a thing as www.cplusplus.com/reference/type_traits/is_same

A
AxisPod, 2014-05-10
@AxisPod

Well, because the whole code is compiled, as if there is no static_if yet, there are workarounds for this. But the problem is that you want to do a compile-time check at run-time, alas, that's not possible.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question