C++ 对引用类型使用比较函数失败
我有一个模板类,如下所示(为了简洁起见,假设使用命名空间std的C++ 对引用类型使用比较函数失败,c++,templates,stl,C++,Templates,Stl,我有一个模板类,如下所示(为了简洁起见,假设使用命名空间std的): 也就是说,映射将type类型的键带到std::set值。当我使用以下方法时,会出现一些问题: void insert(const Type& from, const Type& to, double weight) { //... mapped_type& adj_nodes = backing_map[from]; adj_nodes.insert(make_pair(to,
):
也就是说,映射将type
类型的键带到std::set
值。当我使用以下方法时,会出现一些问题:
void insert(const Type& from, const Type& to, double weight)
{
//...
mapped_type& adj_nodes = backing_map[from];
adj_nodes.insert(make_pair(to, weight));
}
问题是在集合
中,当调用集合_比较
时,它的类型是常量类型&
,而不是类型
。因此,假设它是std::less
,在这种情况下,它将尝试调用less::less(const int&a,const int&b)
,但失败
有没有办法修复它,使两个包含可以(有效地)在这里使用相同的比较函数?Compare
是二进制函子的类型,因此您可能需要
return Compare()(a.first, b.first);
其中,Compare()
是一个临时的、定义构造的Compare
实例。例如,如果将std::less
替换为Compare
std::coutCompare
是二进制函子的类型,因此您可能需要
return Compare()(a.first, b.first);
其中,Compare()
是一个临时的、定义构造的Compare
实例。例如,如果将std::less
替换为Compare
std::cout阅读你的代码并试图理解发生了什么让我头疼。也许你应该更详细地解释这句话:“问题是,在集合中,当它调用set_compare时,它有一个const类型&,而不是type。”阅读你的代码并试图理解发生了什么让我头疼。也许你应该对这句话做更多的解释:“问题是在集合中,当它调用set_compare时,它的类型是const type&,而不是type。”
return Compare()(a.first, b.first);
std::cout << std::boolalpha;
std::cout << std::less<int>(5,50) << "\n"; // Error!
std::cout << std::less<int>()(5,50) << "\n"; // OK