我在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];
}
有什么方法可以使我的功能像我尝试的那样灵活?
该类型Type
在此处分为两点:
template<class Type>
Type GetMedian(const vector<Type>& items, function<bool(Type, Type)> comp);
^^^^ ^^^^^^^^^^
当你调用它GetMedian(v, greater<uint32_t>())
,它就会演绎Type
为uint32_t
对v
,但后来它需要推断function<bool(Type, Type)>
反对greater<uin32_t>
。但是后者不是type function
,因此推论失败。它可以转换为function<bool(uint32_t, uint32_t)>
,但是在模板推导过程中不会进行转换。
幸运的是,您实际上不需要std::function
这里。拥有它实际上更糟-您无缘无故地给自己分配了类型擦除的开销。只是让比较器是一个单独的模板类型:
template <class Type, class Comp>
Type GetMedian(const vector<Type>& items, Comp comp);
或者,如果您真的很想要a std::function
,则可以通过以下方式将其包装Type
在非推导上下文中:
template <class T> struct non_deduced { using type = T; };
template <class T> using non_deduced_t = typename non_deduced<T>::type;
template <class T>
T median(const std::vector<T>&, std::function<bool(non_deduced_t<T>, non_deduced_t<T>)>)
现在,允许从std::greater<uint32_t>
到的转换std::function<bool(uint32_t, uint32_t)>
发生,因为只有vector<T>
那个是推断的上下文,因此编译器推断T
到uint32_t
,然后检查第二个参数转换是否有效。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句