【发布时间】:2016-03-19 17:08:35
【问题描述】:
我有一个函数
template<typename P = int_fast16_t, typename I>
std::vector<std::vector<P>> f(
I xb, I xe, I yb, I ye,
std::function<P(typename std::iterator_traits<I>::value_type,
typename std::iterator_traits<I>::value_type)> &&score_function,
P ID = -1, P S = -1, P M = 1)
它需要两对迭代器和一个函数,该函数应该比较迭代器的 value_type 的两个元素并返回 P 类型的值。
这给了我一个错误
./h.hpp:47:32: note: candidate template ignored: could not match 'function<type-parameter-0-0 (typename iterator_traits<type-parameter-0-1>::value_type, typename iterator_traits<type-parameter-0-1>::value_type)>' against 'stringAlgorithms::scoring::plus_minus_one'
std::vector<std::vector<P>> nw_score_matrix(I xb, I xe, I yb, I ye,
现在,如果我将其更改为使用特定的返回类型 P
template<typename P = int_fast16_t, typename I>
std::vector<std::vector<P>> nw_score_matrix(I xb, I xe, I yb, I ye, std::function<int_fast16_t(typename std::iterator_traits<I>::value_type, typename std::iterator_traits<I>::value_type)> &&score_function, P ID = -1, P S = -1, P M = 1)
这编译。
在这种情况下,函数 plus_minus_one 是
struct plus_minus_one {
template<typename T, typename R = int_fast16_t>
R operator()(const T &x, const T &y) { return x == y ? 1 : -1; }
};
并通过使用
scoring::plus_minus_one matchScoring;
和
nw_score_matrix(x.begin(), x.end(), y.begin(), y.end(), matchScoring);
我意识到我可以在模板中声明一个类型名 F 并将 score_function 设为
F &&score_function
但是我想确保如果有人创建了特定于某些类型的函子/lambda,则该函数处理正确的类型。那么为什么声明不编译呢?
编辑:找到一个完整的例子https://github.com/meconlen/stringAlgorithms/tree/soq
【问题讨论】:
-
你有什么问题?
-
声明确实可以编译,但
function<...>中的内容是非推断上下文。带有typename X<T>::type的任何内容都是参数声明中的非推断上下文。你最好用F&&。 -
您可以将
score_function类型的所有成分类型都设为非推导(例如typename std::common_type<P>::type等)。 -
任何不是
std::function(并且不是从它派生出来的)都可以推导出为std::function。使用类似std::vector<std::vector<typename std::decay<typename std::result_of<F(typename std::iterator_traits<I>::value_type, typename std::iterator_traits<I>::value_type)>::type>::type>> nw_score_matrix(stuff, F&& f)
标签: c++ c++11 std-function