c++ - 在 STL 算法中使用模板谓词的问题

标签 c++ templates stl compiler-errors predicate

我有以下代码,它在 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;
}

http://codepad.org/LRqY3Joq

最佳答案

pred2 是一个普通的函数模板,编译器需要使用特定类型实例化它,可以是现有类型或用户定义类型。

自首次使用以来,编译器无法从空规范中推导出 T 参数。它将标记错误。

对于第二种用法,它是正确的,正如您所指定的那样,编译器通过显式模板规范将 T 模板参数推导为 int。

关于c++ - 在 STL 算法中使用模板谓词的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3083498/

相关文章:

c++ - 在 C++ 中创建新的模板容器类型

c++ - 在类外调用虚函数的语法?

c++ - g++ 未定义对 'Curve:Curve()' 的引用

c++ - 如何将类型名称放入 static_assert 错误中?

c++ - 在 C++ 中搜索 vector 的一部分

c++ - SQL结构与C++ STL映射

c++ - Arduino - 将拆分字符串与另一个字符串进行比较

c++ - python 对象到 native c++ 指针

c++ - 构造函数重载以接受任何函数

c++ - 模板构造函数中的模板类特化