在模板化类中使用 STL 算法(特别是 std::sort) [英] Using STL algorithms (specifically std::sort) from within a templated class
问题描述
我已经声明了一个模板类 MyContainer 如下,然后创建了一个 DataType1 类型的实例.DataType1 类提供了一个友元函数DataSpecificComparison",std::sort 使用它来比较 DataType1 对象.程序编译和排序正确.
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.
然后我定义了一个名为 DataType2 的类,给它一个DataSpecificComparison"的朋友实现,并用它来创建另一个 MyContainer 实例.
I then defined a class called DataType2, gave it a friend implementation of "DataSpecificComparison" and used it to create another instance of MyContainer.
我现在无法将程序编译为C2914:'std::sort':无法推断模板参数,因为函数参数不明确"报告编译时错误.
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.
开发人员如何指定 DataSpecificComparison 二进制谓词采用模板类型 T* 的参数?或者有其他方法可以解决这个问题吗?
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)
}
推荐答案
可以使用所需类型的临时局部函数指针变量来选择DataSpecificComparison
的正确重载:
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);
}
这里编译器可以推断出您要使用与 comparer_t
类型匹配的 DataSpecificComparison
重载,从而解决歧义.
Here the compiler can deduce that you want to use the DataSpecificComparison
overload that matches the comparer_t
type, which resolves the ambiguity.
这篇关于在模板化类中使用 STL 算法(特别是 std::sort)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!