Template Function

Hi! Hope everyone is anxious for the upcoming weekend. I have a quick question regarding templates before the weekend takes over. They are a new topic for me so there is a lack of familiarity. I'm sure the gurus on the forums can assist.

Scenario:

I would like to create a template that takes two different types. One of the types should be a class type that is predefined (a type of histogram for example) and the other is just a type of vector (i.e double, unsigned, etc):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
template <typename HistType, typename VecType>
void Plot(const VecType & histdata, const char* name, const char* title, const int num_bin, const VecType bin_min, const VecType bin_max)
{
HistType * hist = new HistType(name, title, num_bin, bin_min, bin_max);
for (typename VecType::iterator it = histdata.begin(); it != histdata.end(); ++it)
{ hist->Fill(*it); }


// set hist characteristics
hist -> SetFillColor(kBlue-6);
hist -> SetXTitle(name);
hist -> SetYTitle("Frequency");
hist -> Write(title);
delete hist;
hist = 0;

};


When I call the template function, I use:

Plot< TH1D, vector<double> >(v_R13x_slopes, name.c_str(), title.c_str(), 100, 1.0, 500.0);

Unfortunately, I get a compile error:

1
2
main.cpp:2408: error: no matching function for call to ‘Plot(std::vector<double, std::allocator<double> >&, const char*, const char*, int, double, double)’
make: *** [main.o] Error 1



Here I'm not sure to what
std::allocator<double> >&
is referring. Hopefully, I didn't murder the code to badly. If someone could point me in the right direction, I'd appreciate it.


Have a great weekend!

T.
Last edited on
STL containers have a default template parameter for memory management called an allocator. You can just ignore the fact that it shows up in the error message. The error message that you have is telling you what types are passed to the function when you call it. If you compare those types to the function's signature, you'll see that the last two arguments were VecType (vector<double>) not just doubles.

Consider using something like typename VecType::value_type for the contained type (double).
Last edited on
You don't need this < TH1D, vector<double> > after Plot. The compiler can determine from the paramter provided what type is used.

You tell the compiler that 'VecType' ist 'vector<double>' but the paramters aren't vectors just single value. So you have mismatch

EDIT:
Hope everyone is anxious for the upcoming weekend
Um, why?
Last edited on
Thanks for the responses. They worked like a charm!!
Topic archived. No new replies allowed.