template method in c++
-
There are three list which include objects of my classes.(car,bus,lorry) All the objects have an unique id number. I want to find the object which has a id that has given as parameter. (as using template method of c++) For example my classes are; class car{ string colour1; int id; int weight1; } class bus{ string colour2; int id; int weight2; } class lorry{ string colour3; int id; int weight3; } Is it necessary to write same names of the variables (id) to apply template method to my application? Thanks.
-
There are three list which include objects of my classes.(car,bus,lorry) All the objects have an unique id number. I want to find the object which has a id that has given as parameter. (as using template method of c++) For example my classes are; class car{ string colour1; int id; int weight1; } class bus{ string colour2; int id; int weight2; } class lorry{ string colour3; int id; int weight3; } Is it necessary to write same names of the variables (id) to apply template method to my application? Thanks.
I assume you mean something like this:
template <typename T>
inline int GetID(const T &obj)
{
return obj.id;
}There are a number of methods you could use to handle differently named variables. Given the general case above you could introduce an exception using template specialisation as follows for example:
template <>
inline int GetID<rocket>(const rocket &obj)
{
return obj.rocket_id;
}Steve
-
I assume you mean something like this:
template <typename T>
inline int GetID(const T &obj)
{
return obj.id;
}There are a number of methods you could use to handle differently named variables. Given the general case above you could introduce an exception using template specialisation as follows for example:
template <>
inline int GetID<rocket>(const rocket &obj)
{
return obj.rocket_id;
}Steve
carList for car busList for bus lorryList for lorry I have a method; int find(type list, int id) //type can be three posibilities (carList,busList,lorryList) { for(i){ if(list[i].id == id){ return id; } } } Is this method right for my porpose as logical?
-
carList for car busList for bus lorryList for lorry I have a method; int find(type list, int id) //type can be three posibilities (carList,busList,lorryList) { for(i){ if(list[i].id == id){ return id; } } } Is this method right for my porpose as logical?
I can't tell. Is it a template? It doesn't look like one. What is
type
?Steve