• Advertisement
Sign in to follow this  

typeid type_info help please

This topic is 981 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi Guys,

 

Given a set of items all derived from a "BaseItem" class in a container such as

std::vector<BaseItem*> items

I would like to construct a function like this:

bool isTypeInList(Unknown parameter){

 for(auto it=items.begin();it!=items.end();it++)

   if(typeid(*unknown parameter)==typeid(it)

      return true;

return false;

}

Basically I need to stick a typeid(Torch), typeid(Spear) etc. into the parameter and test if it's in items list.

 

 

Share this post


Link to post
Share on other sites
Advertisement
You can pass in a type_info object:

http://ideone.com/aSxlk9
#include <iostream>
#include <typeinfo>
using namespace std;

struct A { virtual ~A() {}; virtual void foobar() {} };
struct B : A { };
struct C : A { };
struct D : A { };

bool contains_type( A** arr, int ct, const type_info& a ) {
    for ( int idx = 0; idx < ct; ++idx ) {
    	if ( a == typeid(*arr[idx]) )
    		return true;
    }
    
    return false;
}

int main() {
	B b;
	C c;
	D d;
	
	const int ct = 2;
	A* arr[ct] = {&b, &c};
	
	cout << contains_type(arr,ct,typeid(B)) << endl;
	cout << contains_type(arr,ct,typeid(C)) << endl;
	cout << contains_type(arr,ct,typeid(D)) << endl;
	return 0;
}
Of course, this is a bit of a code smell. Why not have a 'type' attribute as a string within the BaseItem itself and query against that? It'd be less cumbersome as A*, A&, and A are have different type_infos, despite being "the same" in regards to what you're trying to do here. Edited by fastcall22

Share this post


Link to post
Share on other sites
Consider alternatives too:
  • If the type turns out to be important, are you sure you want to lose track of it by storing it in a list of other stuff?
  • Is it possible to covert this from a type query to a virtual function call?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement