【发布时间】:2010-06-21 09:37:03
【问题描述】:
我有以下一段代码,它在 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>());
标签: c++ templates stl compiler-errors predicate