开发者

functor in header file

I have the following f开发者_运维知识库unctor and I had included it in my main program

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;
 }
};

It wasn't giving any error when it was in the .cpp, but now when I moved it to my .h, it gives me the following error:

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

So, I rewrote it as:

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;
 }
};

and now i get the following error:

testclass.h: At global scope:
testclass.h:50:30: error: expected initializer before ‘:’ token

any suggestion on how I can fix it? thanks!


The original error is probably with binary_function: missing the include or not considering that it is in namespace std.

#include <functional>

and

std::binary_function<T, T, int>


template<class T> T Comp: public binary_function<T, T, int> is not valid syntax, the first one is correct. The error is probably about binary_function — make sure you included the header and it should be std::binary_function.

Also, binary_function is largely useless, especially in C++11.


template<class T> T Comp : public binary_function<T, T, int>
               //^^^ what is this?

What is that? That should be struct (or class).

Also, have you forgotten to include <functional> header file in which binary_function is defined?

Include <functional>. And use std::binary_function, instead of binary_function as:

#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;
 }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜