I will open the question with a code sample:
template <template <class, class> class Container>
class Schedule {
public:
Schedule& print( std::ostream& os);
private:
Container<Course*, std::allocator<Course*> > courses;
};
// implement funcion print:
template <template <class, class> class Container>
Schedule<Container>& Schedule<Container>::print(std::ostream& os){
std::sort(courses.begin(), courses.end(), sor_con());
std::for_each(courses.begin(), courses.end(), PrintContainer(os));
return *this;
}
template<>
Schedule<std::list>& Schedule<std::list>::print(std::ostream& os){
courses.sort(sort_con());
std::for_each(courses.begin(), courses.end(), PrintContainer(os));
return *this;
}
The Schedule
class contains template classes (std::list / std::vector
) only. Because the print
function needs to use sort, I need use two different ways to implement this: std::sort
from for std::vector
and sort
function of list container for std::list
.
My code works, but I think I created unnecessary code duplication here. Is there a more efficient way to solve this problem?