【发布时间】:2016-03-08 16:38:58
【问题描述】:
我在 C++ 中定义了以下函数:
template<class Type> Type GetMedian(const vector<Type>& items, function<bool(Type, Type)> comp) {
vector<Type> copied_items(items);
std::nth_element(copied_items.begin(), copied_items.begin() + copied_items.size()/2, copied_items.end(), comp);
return copied_items[copied_items.size()/2];
}
但是,当我尝试将其称为 GetMedian(v, greater<uint32_t>()) 时,我的编译器 (clang) 会抱怨:
error: no
matching function for call to 'GetMedian'
GetMedian(v, greater<uint32_t>());
^~~~~~~~~
note:
candidate template ignored: could not match 'function' against 'greater'
template<class Type> Type GetMedian(const vector<Type>& items, function...
但是,每当我更改为不使用模板时,我都没有看到此错误,因为:
uint32_t GetMedian(const vector<uint32_t>& items, function<bool(uint32_t, uint32_t)> comp) {
vector<uint32_t> copied_items(items);
std::nth_element(copied_items.begin(), copied_items.begin() + copied_items.size()/2, copied_items.end(), comp);
return copied_items[copied_items.size()/2];
}
有什么方法可以让我的功能像我想要的那样灵活吗?
【问题讨论】:
-
您是否希望模板强制提供的比较函数与向量具有相同的类型,或者如果使用不正确的比较函数会在类型不同时生成编译器错误/警告,是否可以?
-
我怀疑这是一个不可演绎的上下文问题。您可以通过明确使用模板参数来解决此问题。
GetMedian<uint32_t>(...).
标签: c++ templates generics lambda