首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >头文件中的functor

头文件中的functor
EN

Stack Overflow用户
提问于 2011-08-23 00:42:54
回答 3查看 1.2K关注 0票数 0

我有下面的函数式,我已经把它包含在我的主程序中了

代码语言:javascript
复制
template<class T> struct Comp: public binary_function<T, T, int>
{
 int operator()(const T& a, const T& b) const
 {
   return (a>b) ? 1: (a<b) ? -1 :0;
 }
};

当它在.cpp中时,它没有给出任何错误,但现在当我将它移到我的.h中时,它给出了以下错误:

代码语言:javascript
复制
testclass.h: At global scope:
testclass.h:50:59: error: expected template-name before ‘<’ token
testclass.h:50:59: error: expected ‘{’ before ‘<’ token
testclass.h:50:59: error: expected unqualified-id before ‘<’ token

因此,我将其重写为:

代码语言:javascript
复制
template<class T> T Comp: public binary_function<T, T, int>
{
 int operator()(const T& a, const T& b) const
 {
   return (a>b) ? 1: (a<b) ? -1 :0;
 }
};

现在我得到了以下错误:

代码语言:javascript
复制
testclass.h: At global scope:
testclass.h:50:30: error: expected initializer before ‘:’ token

有什么建议可以帮我解决这个问题吗?谢谢!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-08-23 00:44:57

最初的错误可能与binary_function有关:缺少include,或者没有考虑到它在名称空间std中。

代码语言:javascript
复制
#include <functional>

代码语言:javascript
复制
std::binary_function<T, T, int>
票数 6
EN

Stack Overflow用户

发布于 2011-08-23 00:46:07

template<class T> T Comp: public binary_function<T, T, int>不是有效语法,第一个语法是正确的。该错误可能与binary_function有关-请确保您包含了标头,并且它应该是std::binary_function

而且,binary_function在很大程度上是无用的,尤其是在C++11中。

票数 4
EN

Stack Overflow用户

发布于 2011-08-23 00:46:45

代码语言:javascript
复制
template<class T> T Comp : public binary_function<T, T, int>
               //^^^ what is this?

那是什么?这应该是struct (或class)。

另外,您是否忘记包含定义binary_function<functional>头文件?

包括<functional>。并使用std::binary_function代替binary_function,如下所示:

代码语言:javascript
复制
#include <functional> //must include

template<class T> struct Comp: public std::binary_function<T, T, int>
{                                   //^^^^^ qualify it with std::
 int operator()(const T& a, const T& b) const
 {
   return (a>b) ? 1: (a<b) ? -1 :0;
 }
};
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7150687

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档