Using STL algorithms (specifically std::sort) from within a templated class
c++, sorting, stl, templates
Solution
You can use a temporary local function pointer variable of the required type to select the correct overload of `DataSpecificComparison`:
void SortMyContainerObjects()
{
typedef bool (*comparer_t)(const T*, const T*);
comparer_t cmp = &DataSpecificComparison;
std::sort(m_vMyContainerObjects.begin(), m_vMyContainerObjects.end(), cmp);
}
Here the compiler can deduce that you want to use the `DataSpecificComparison` overload that matches the `comparer_t` type, which resolves the ambiguity.
Problem
I've declared a template class MyContainer as bellow, then created an instance of it of type DataType1. The DataType1 class provides a friend function "DataSpecificComparison" which is used by std::sort to compare DataType1 objects. The program compiled and sorted correctly. I then defined a class called DataType2, gave it a friend implementation of "DataSpecificComparison" and used it to create another instance of MyContainer. I am now unable to compile the program as a "C2914: 'std::sort' : cannot deduce template argument as function argument is ambiguous" compile time error is reported. How can a developer specify that the DataSpecificComparison binary predicate is to take arguments of template type T*? Or is there another way around this issue? ``` template <class T> class MyContainer { private: vector<T*> m_vMyContainerObjects; .... public: .... void SortMyContainerObjects() { std::sort(m_vMyContainerObjects.begin(), m_vMyContainerObjects.end(), DataSpecificComparison) } } class DataType1 { .... friend bool DataSpecificComparison(const DataType1 * lhs, const DataType1 * rhs) } class DataType2 { .... friend bool DataSpecificComparison(const DataType2* lhs, const DataType2* rhs) } ```