问题在STL算法中使用模板谓词 [英] Problem using templated predicate in STL algorithms

查看:165
本文介绍了问题在STL算法中使用模板谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码,在pred2的第一个使用形式上给出错误。我希望如果有人可以解释为什么这个特定的用法是不正确的,因为我认为pred3的用法是类似的。

I have the following piece of code, that gives an error on the first usage form of pred2. I was hoping if someone could explain why this particular usage is incorrect, as I think pred3 usage is similar.

#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是一个正常的函数模板并且编译器需要使用可以是现有类型或用户定义类型的特定类型来实例化它。

pred2 is a normal function template and compiler needs to instantiate it using a particular type which can be existing type or user defined type.

由于在第一次使用时,编译器不能从空规范。它会标记一个错误。

Since in first usage, compiler is not able to deduce T argument from empty specification. It will flag an error.

第二次使用时,它的权利,正如你指定的编译器通过显式模板规范将T templete参数推导为int。

With second usage, its right, as you have specified by which compiler deduces T templete argument to int through explicit template specification.

这篇关于问题在STL算法中使用模板谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆