Object check from TFile

I have a TFile that has some TH1 and TH2 histograms written to them. I also have the following loop:

TList *list = File -> GetListOfKeys(); TObject *obj = NULL; for(int l = 0; l < File->GetNkeys(); l++){ obj = (TObject*)histlist->At(l); . . . }

I want to include a conditional in the above for loop that has a set of instructions if the object is a TH1 and a different set of instructions if it is a TH2. I was wondering what the best way to do this check was? I know I can check the names of the objects, but I was wondering if there was something better? Thanks in advance.

Hi,

you can use ROOT RTTI to achieve this goal, i.e.:

TFile f("f.root");

auto th1fTClassPtr = TH1F::Class();
auto keysPtr = f.GetListOfKeys();

for(auto&& keyAsTObj : *keysPtr){
   auto key = (TKey*) keyAsTObj;
   auto obj = key->ReadObj();
   if (th1fTClassPtr == obj->IsA()){
      cout << "Object " << obj->GetName() << " is a TH1F instance.\n";
   }
}

Cheers,
Danilo

Hi dpiparo,

Thanks for your response. I am not at all familiar with ROOT RTTI, so my apologies if this question seems ignorant. I get the following error and am not sure what to do about it:

error: invalid range expression of type 'TList'; no viable 'begin' function available for(auto&& keyAsTObj : *keysPtr){ ^ ~

Hi,

what version of ROOT are you using?
That syntax is only possible with recent 5.34 or a 6 ROOT version. If you can not move to a more recent version, a non-range based loop shall be used.

Cheers,
Danilo

I am using ROOT 5.34.

Hi,

what version of it?
If you are not sure, just type “gROOT->GetVersion()” at the prompt.

Danilo

It is 5.34/09.

Hi,

Range based looping was not supported back then (2013). Yiou can solve the issue moving to a recent version, eg 6.04.06 or 5.34.34.

Danilo