【发布时间】:2018-09-21 03:58:11
【问题描述】:
为什么我需要在函数的定义中使用 2 个模板,一个用于每个二元谓词?
我写了一个和std::min_element或std::max_element几乎一样的函数,只是不是返回1个元素,而是返回所有等于那个限制(或min,或最大)
我上次阅读 boost::minmax_element.hpp,我复制了函数并更改了输出和 while 循环来创建函数。
并且如果我使用
有效if( *first > *lim.front() )
但不是如果我使用
if( comp(*first, *lim.front()) )
这里是函数
template <typename INPUT_ITERATOR, class Compare>
std::vector<INPUT_ITERATOR>
basic_limit_positions( INPUT_ITERATOR first, INPUT_ITERATOR last, Compare comp, Compare comp_equal ) {
std::vector<INPUT_ITERATOR> lim;
if ( first == last ) {
lim.push_back( last );
return lim;
}
lim.push_back(first);
while (++first != last) {
if ( comp( *first, *lim.front() ) ) {
lim.clear();
lim.push_back( first );
}
else if ( comp_equal( *first, *lim.front() ) )
lim.push_back( first );
}
return lim;
}
我如何使用它:
std::vector< std::vector<uint64_t>::iterator > it = basic_limit_positions(v.begin(),
v.end(),
std::greater< uint64_t >(),
std::equal_to< uint64_t > ()
);
还有错误:
test.cpp:40:80: error: no matching function for call to ‘basic_limit_positions(std::vector<long unsigned int>::iterator, std::vector<long unsigned int>::iterator, std::greater<long unsigned int>, std::equal_to<long unsigned int>)’
);
^
In file included from test.cpp:10:0:
newton/algorithm/superior_positions.hpp:7:1: note: candidate: template<class INPUT_ITERATOR, class Compare> std::vector<INPUT_NUMBER> basic_limit_positions(INPUT_ITERATOR, INPUT_ITERATOR, Compare, Compare)
basic_limit_positions( INPUT_ITERATOR first, INPUT_ITERATOR last, Compare comp, Compare comp_equal ) {
^~~~~~~~~~~~~~~~~~~~~
newton/algorithm/superior_positions.hpp:7:1: note: template argument deduction/substitution failed:
test.cpp:40:80: note: deduced conflicting types for parameter ‘Compare’ (‘std::greater<long unsigned int>’ and ‘std::equal_to<long unsigned int>’)
);
^
所以我认为:“问题出在模板上,因为如果为参数 'Compare' 推断出冲突类型,并且类型正确,则唯一的剩余大小写正在更改模板名称”
template <typename INPUT_ITERATOR, class Compare1, class Compare2>
std::vector<INPUT_ITERATOR>
basic_limit_positions( INPUT_ITERATOR first, INPUT_ITERATOR last, Compare1 comp, Compare2 comp_equal )
而且...有效,但是¿?它是相同的类型,所以我使用相同的模板名称来first和last为什么!? comp 和 comp_equal
不能使用相同的名称对我来说真的没有意义。
【问题讨论】:
-
您的模板需要两个不同的比较器模板参数,一个用于
comp,另一个用于comp_equal。虽然根本不需要两个比较器,因为可以仅从comp找出相等性。 -
怎么样?你不能使用 !comp
-
!((a < b) || (b < a)) -
是的!我改了,
if( comp( *first, *limit.front() ) )else if( !comp( *limit.front(), *first ) ),和!((a < b) || (b < a))一样,因为De Morgan(!(a < b) && !(b < a))
标签: c++ templates functional-programming