我有以下代码片段,在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;
}
template<typename T> struct pred4 { bool operator()(T&) {return true;} };
会导致相同的问题。你需要将它作为std::count_if(A, A + N, pred4<int>())
传递进去。 - sbi