【发布时间】:2017-12-22 21:52:57
【问题描述】:
我想根据传递的函子来约束模板参数。考虑这个来自某些容器类型的FoldLeft 函数:
template<typename F, typename R>
R FoldLeft(F&& functor, R initialValue) {
R r = initialValue;
/* assume that this is a range of uint64_t's */
while (first != last) {
r = std::forward<F>(functor)(r, *(first++));
}
return r;
}
这个函数可以这样调用:
auto sum = FoldLeft([](uint64_t i, auto& e) { return e + i; }, 0);
这里的问题是R 是从initialValue 参数推导出来的,在这种情况下是0,因此导致int。同样decltype(sum) 也给出int。
我想将R 推导出为函子的返回类型,它可以是 lambda 或任何其他可调用类型。我已经尝试过使用this answer的方法,但总是遇到这个错误:
error: decltype cannot resolve address of overloaded function
struct function_traits
^~~~~~~~~~~~~~~
note: substitution of deduced template arguments resulted in errors seen above
我尝试的代码(fuction_traits 复制自链接答案):
template<typename T>
using LamRet = typename function_traits<T>::result_type;
template<typename F>
LamRet<F> FoldLeft(F&& functor, LamRet<F> initialValue) {
LamRet<F> r = initialValue;
/* assume that this is a range of uint64_t's */
while (first != last) {
r = std::forward<F>(functor)(r, *(first++));
}
return r;
}
【问题讨论】:
-
从
first/last获取这些信息比按照你的建议去做要容易得多。 -
如果您不使用
auto作为 lambda 中的参数也没问题,您的代码将正常工作
标签: c++ c++11 templates lambda