const_cast & typeid

This two instructions are very useful in some situations, for example when you have a function that receives a const parameter, but your variable is not const.

The second one could be useful, but I think it's better not to use it if we want agnostic code.

The following documentation is from http://www.cplusplus.com/doc/tutorial/typecasting/

Const_cast

This type of casting manipulates the constness of an object, either to be set or to be removed. For example, in order to pass a const argument to a function that expects a non-constant parameter.


// const_cast
#include <iostream>
using namespace std;

void print (char * str)
{
  cout << str << endl;
}

int main () {
  const char * c = "sample text";
  print ( const_cast<char *> (c) );
  return 0;
}

Typeid

typeid allows to check the type of an expression: 
typeid (expression)
This operator returns a reference to a constant object of type& type_info that is defined in the standard header file <typeinfo>
This returned value can be compared with another one using operators == and  !=  or can serve to obtain a null-terminated character sequence representing the data type or class name by using its name() member.

// typeid
#include <iostream>
#include <typeinfo>
using namespace std;

int main () {
  int * a,b;
  a=0; b=0;
  if (typeid(a) != typeid(b))
  {
    cout << "a and b are of different types:\n";
    cout << "a is: " << typeid(a).name() << '\n';
    cout << "b is: " << typeid(b).name() << '\n';
  }
  return 0;
}


When  typeid is applied to classes typeid uses the RTTI to keep track of the type of dynamic objects. When typeid is applied to an expression whose type is a polymorphic class, the result is the type of the most derived complete object

Comentarios

Entradas populares