c++ - 无法从函数参数的默认参数中推断出模板参数

标签 c++ templates c++11

我正在尝试创建一个函数来查找满足给定条件的范围内的最小元素:

#include <functional>
#include <iostream>
#include <vector>

template <typename It, typename Pred, typename Comp>
It minElementWhere(
    It begin,
    It end,
    Pred pred = Pred(),

    // Use less-than as the default comparator.
    Comp comp = std::less<decltype(*std::declval<It>())>()
) {
    It minElement = end;

    for (It it = begin; it != end; ++it) {
        if (!pred(*it)) {
            continue;
        }

        if (comp(*it, *minElement)) {
            minElement = it;
        }
    }

    return minElement;
}

int main() {
    std::vector<double> foo;
    foo.push_back(6);
    foo.push_back(10);
    foo.push_back(-3);
    foo.push_back(7);

    std::cout << *minElementWhere(
        foo.begin(),
        foo.end(),
        [](double val) {
            return val >= 0;
        }
    ) << std::endl;
}

但是我得到这个错误:

main.cpp: In function 'int main()':
main.cpp:40:5: error: no matching function for call to 'minElementWhere(std::vector<double>::iterator, std::vector<double>::iterator, main()::__lambda0)'
     ) << std::endl;
     ^
main.cpp:40:5: note: candidate is:
main.cpp:6:4: note: template<class It, class Pred, class Comp> It minElementWhere(It, It, Pred, Comp)
 It minElementWhere(
    ^
main.cpp:6:4: note:   template argument deduction/substitution failed:
main.cpp:40:5: note:   couldn't deduce template parameter 'Comp'
     ) << std::endl;

Comp 不是返回类型,因此它不会尝试推断返回类型,而且在我看来,Comp 也没有模棱两可的重载(因为只能有一种取消引用 It 的返回类型)。为什么会出现此错误,我该如何解决?

最佳答案

您期望模板参数 Comp 是从您为相应函数参数提供的默认参数中推导出来的。但是,这被明确列为非推导上下文,这意味着该模板参数的模板参数推导将失败(除非它可以从其他地方推导)。

来自 §14.8.2.5/5 [temp.deduct.type]

The non-deduced contexts are:
— ...
— A template parameter used in the parameter type of a function parameter that has a default argument that is being used in the call for which argument deduction is being done.

要成功推导模板参数,请为模板参数提供默认参数,而不是函数参数。

template <typename It, 
          typename Pred, 
          typename Comp = std::less<decltype(*std::declval<It>())>>
It minElementWhere(
    It begin,
    It end,
    Pred pred = Pred(),
    Comp comp = Comp()
) {
...
}

Live demo

关于c++ - 无法从函数参数的默认参数中推断出模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24277974/

相关文章:

c++ - 在 makefile 中列出 .cpp 或 .o

c++ - 如何从 C++ 使用 FTGL C API?

c++ - 如何在C++中创建使用给定伪代码递归的可变参数函数?

c++ - 创建库以覆盖迭代器的 operator*() - 风险悬空指针

c++ - C++11中通过pthreads获取线程Core affinity

c++ - Dart 编译错误 - 代码库中的奇怪代码片段

c++ - 如何将用 C++ 编写的 Qt4 小部件实现到一些 Python 代码中?

c++使用方法作为函数的参数

templates - Meteor 模板和模板助手

c++ - 如何在不指定模板参数的情况下将 lambda 与模板参数匹配