3

I would like to know if doing the following is safe:

template<class T>
void Parameters::add(Parameter<T> p)
{
   std::string sprobe("");
   int iprobe = 0;
   double dprobe = 0.;

   if (typeid(T) == typeid(sprobe))
     this->mstrings[p.name()] = p;

   if (typeid(T) == typeid(iprobe))
     this->mints[p.name()] = p;

   if (typeid(T) == typeid(dprobe))
     this->mdoubles[p.name()] = p;
}

I have a Class for storing parameters. It has 3 boost::unordered_map member variables for storing parameters of type int, double and std::string;

I created a template class Parameter.

I understand that if my Parameter is not one of the 3 types that I anticipated this will fail. But it is not a problem since I know that the Parameters can only be of these types.

Thanks for your help

tvery42
  • 31
  • 1
  • 1
  • 3

2 Answers2

5

The code won't compile, but not because of typeid. The problem is that even with the correct if-clauses, the code of your method needs to be compiled - all of it. That is independent of whether or not a part of the code is executed (=evaluated) or not. This leads to the problem that if T is int, you still need to be able to compile the code for the other cases, e.g., this line:

this->mstrings[p.name()] = p;

The type of mstrings is very likely incompatible with passing Parameter<int> as p, hence you will get a compile error.

The solution is to use overloading where each method must only compile one case, but not the others, example for int:

void Parameters::add(Parameter<int> p)
{
    this->mints[p.name()] = p;
}

and likewise for the other cases.

Final note: Even if you use typeid, you don't need the probes. You can simply use typeid(int) directly.

Daniel Frey
  • 55,810
  • 13
  • 122
  • 180
0

Ignoring whether that is a good programming practice or not ...

Your program is safe from the language point of view. Comparison of type_info, the valued returned by the typeid operator, is well defined in the standard:

18.5.1 Class type_info

...

bool operator==(const type_info& rhs) const;

2 Effects: Compares the current object with rhs.

3 Returns: true if the two values describe the same type.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270