Is possible get histogram class name from the TFile?

Dear rooters,

I have to deal with different root files, and people sometimes creates TH1F, sometimes TH1D.

In the beginning of my analysis program, I check if the histograms exist before copying them

  TH1 * h_copy = NULL;
  if( inputFile->GetObjectChecked( "myHistogram", "TH1D") )
    h_copy = ( (TH1D*) f->GetObjectChecked( "myHistogram" "TH1D"))->Clone();
  else if ( inputFile->GetObjectChecked( "myHistogram", "TH1F") )
     h_copy = ( (TH1F*) f->GetObjectChecked( "myHistogram" "TH1F"))->Clone();
  else 
      std::cerr << "!-> Error" << std::endl;

I wonder if there is a more elegant way (a template way?) of copying histograms. Will it fail if I use TH1 * h_copy, instead of the proper class (TH1F vs TH1D)?

Thank you in advance.

Greetings.

[quote]Will it fail if I use TH1 * h_copy, instead of the proper class (TH1F vs TH1D)? [/quote]Short answer: yes.

Instead of GetObjectChecked, you could use GetKey and ask the key for the classname.

The following code is strictly equivalent (thanks to inheritance and overloading to your code);

TH1 * h_copy = NULL; if( inputFile->GetObjectChecked( "myHistogram", "TH1") ) h_copy = ( (TH1*) f->GetObjectChecked( "myHistogram" "TH1"))->Clone(); else std::cerr << "!-> Error" << std::endl;

If you intend is simply to load the histogram and transfer ownership from the TFile to you, the following code should work:

TH1 * h_copy = nullptr; inputFile->GetObject("myHistogram",h_copy); if (h_copy) // we do have a TH1 h_copy->SetDirectrory(nullptr); else std::cerr << "!-> Error" << std::endl;

Cheers,
Philippe.

Hello

Thank you for the clarification and the snippet :slight_smile:

Greetings.