加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 具有功能类型的模板参数原因编译器错误

发布时间:2020-12-16 10:01:59 所属栏目:百科 来源:网络整理
导读:我在C中定义了以下函数: templateclass Type Type GetMedian(const vectorType items,functionbool(Type,Type) comp) { vectorType copied_items(items); std::nth_element(copied_items.begin(),copied_items.begin() + copied_items.size()/2,copied_item
我在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,更大< 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(),comp);
  return copied_items[copied_items.size()/2];
}

有没有办法让我的功能像我想的那样灵活?

解决方法

Type类型在这里有两个点:

template<class Type> 
Type GetMedian(const vector<Type>& items,Type)> comp);
                            ^^^^                        ^^^^^^^^^^

当你用GetMedian(v,更大< uint32_t>())调用它时,它会为v推导出类型为uint32_t,但是它需要推导出函数< bool(Type,Type)>反对更大< uin32_t>.但后者不是类型函数,因此推论失败.它可以转换为函数< bool(uint32_t,uint32_t)>,但在模板推导过程中不会发生转换.

谢天谢地,你实际上并不需要这里的std :: function.它实际上更糟糕 – 你无缘无故地给自己带来类型擦除的开销.只需将比较器作为单独的模板类型:

template <class Type,class Comp>
Type GetMedian(const vector<Type>& items,Comp comp);

或者,如果你真的真的想要一个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)>允许发生,因为它只是向量< T>.这是推导的上下文,因此编译器将T推导为uint32_t,然后检查第二个参数转换是否有效.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读