samedi 5 décembre 2015

Polymorphism in std::vector with non-member functions

I've already tried to post this problem, but everyone complained, how my problem is hard to understand and asked me to provide an MCVE, so I've decided to ask this question again with an example provided:

http://ift.tt/1NaLoUr

I have a problem, that I came across. I am working in C++11 with Root, and I have a std::vector which contains variables (histograms) of type TH1D* and TH2D*. I am not allowed to touch the TH1D or TH2D definitions, but I am doing different things based on the type of the variable.

Whenever I want to call an overloaded function, that would handle both cases, my compiler cries out saying "call of overloaded function is ambiguous"... I know it is, but I need help figuring out a better design... How should I do it?

My problem in the code:

void save_histograms_from_vector( const std :: vector<TH1*>& histogram_vector_p )
{
    for( auto& histogram: histogram_vector_p )
    {
        save_histogram_as_canvas( histogram ); //overloaded function
    }
}
(...)
template<typename TH_type_1, typename TH_type_2, typename TH_type_3, typename TH_type_4> 
void save_as_two_by_two_canvas( TH_type_1 histogram_1_p, TH_type_2 histogram_2_p, TH_type_3 histogram_3_p, TH_type_4 histogram_4_p, TFile* output_file_p, const std :: string& directory_name_p, const std :: string& canvas_name_p, const std :: string& canvas_title_p )
{
     (...)
     const std :: vector<TH1*> histograms = { histogram_1_p, histogram_2_p, histogram_3_p, histogram_4_p };
     save_histograms_from_vector( histograms );
     // This would have worked if I called the function Write() for each of the histograms )
}

So, as for the example, my goal is to write functions that can achieve what the message_of_instances() function should do. The example now does not compile, but the only thing it has a problem with, is that it can not deduce the type of the elements in the std :: vector. If I were to call a member function of the elements, like simply write() works.

My question is: Is there a workaround for these kinds of problems?

Thank you for all the constructive comments!!

Aucun commentaire:

Enregistrer un commentaire