2011-08-22 61 views
0

我有以下函子和我在我的主要程序包括它算符,頭文件

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,它給了我下面的錯誤:

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 

所以,我重寫它:

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

,現在我得到以下錯誤:

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

有關我如何修復它的任何建議?謝謝!

回答

6

原始錯誤可能與binary_function:錯過包含或不包含它在命名空間std

#include <functional> 

std::binary_function<T, T, int> 
+0

不包括的std ::是我的錯....我有包括... THX UncleBens :-) – itcplpl

4

template<class T> T Comp: public binary_function<T, T, int>是無效的語法中,第一個是正確的。該錯誤可能是大約binary_function - 確保您包含標題,它應該是std::binary_function

另外,binary_function在很大程度上是無用的,特別是在C++ 11中。

+0

是的,性病::是問題: - (...所以如果binary_function是無用的,我只是消除它或被其他東西替換 – itcplpl

+0

@itcplpl:如果你使用'bind'(無論'boost :: bind'或'std :: bind'), –

+0

好吧,我會與std :: bind-thx一起工作:-) – itcplpl

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

那是什麼?那應該是struct(或class)。

此外,您是否忘記了包含<functional>其中binary_function被定義的頭文件?

包括<functional>。並使用std::binary_function,而不是binary_function爲:

#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

是的,修正了.... thx Nawaz – itcplpl

+0

你能告訴我這個代碼的錯誤是什麼:class cmp_test { public: bool operator()(const test&a,const test&b ) { return a itcplpl

+0

@itcplpl:這個錯誤意味着,你必須爲'test'類類實現'operator <'。你有沒有定義它?如果不是,請定義它。如果是,那麼簽名是什麼? – Nawaz