我有以下代码,它在 pred2 的第一种使用形式上给出了错误。我希望有人能解释为什么这种特定用法不正确,因为我认为 pred3 用法是相似的。
#include <algorithm>
bool pred1(const int&) { return true; }
template<typename T>
bool pred2(const T&) { return true; }
struct pred3
{
template<typename T>
bool operator()(T&) { return true; }
};
int main()
{
int A[] = { 2, 0, 4, 6, 0, 3, 1, -7 };
const int N = sizeof(A) / sizeof(int);
std::count_if(A, A + N, &pred1); //ok
std::count_if(A, A + N, &pred2); //error
std::count_if(A, A + N, &pred2<int>); //ok
std::count_if(A, A + N, pred3()); //ok
return 0;
}
最佳答案
pred2 是一个普通的函数模板,编译器需要使用特定类型实例化它,可以是现有类型或用户定义类型。
自首次使用以来,编译器无法从空规范中推导出 T 参数。它将标记错误。
对于第二种用法,它是正确的,正如您所指定的那样,编译器通过显式模板规范将 T 模板参数推导为 int。
关于c++ - 在 STL 算法中使用模板谓词的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3083498/