2012-10-14 97 views
1

我有我傳遞給std::sort算法以下比較函數來排序對象的矢量:模板比較函數

template <typename PointT> 
bool myCompareLines (A<PointT>::model_struct model_a, A<PointT>::model_struct model_b) { 
    return (/* some comparison code*/); 
} 

比較功能。該聲明的類之外,我稱它是這樣:

template <typename PointT> 
class B { 
    [...] 
    std::sort(lines.begin().lines.end(),::myCompareLines); 
    [...] 
} 

我編譯時出現錯誤:template declaration of 'bool myCompareLines'

裏面class A我declar e class B作爲朋友類,以便class B可以 訪問私人類型model_struct。我錯過了什麼?

+1

'myCompareLines'是一個模板,而不是一個函數。 –

+0

感謝所有回答的人,我在myCompareLines的簽名中缺少了typename關鍵字。所以它應該是: – Mustafa

+0

bool myCompareLines(typename A :: model_struct model_a,typename A :: model_struct model_b) – Mustafa

回答

1

我在CompareLines簽名中缺少typename關鍵字。

此修復它:

bool myCompareLines (typename A<PointT>::model_struct model_a, typename B<PointT>::model_struct model_b) 
0

編譯器無法從內部類A<PointT>::model_struct推導出模板參數PointT

它不能因爲A<PointT>許多專業化可以有相同的model_struct - 樣:

template <class PointT> 
class A { 
public: 
    typedef int model_struct; 
}; 

這個例子:

int a; 
    bool res = compareLines(a,a); 

定義model_struct作爲頂級模板。

1

你不應該只是做:

template <typename PointT> 
class B { 
    [...] 
    std::sort(lines.begin(), lines.end(), ::myCompareLines<PointT>); 
    [...] 
} 
2

雖然可怕,是你在找什麼?注意:編譯並不等於好。即使這對你有用,我會建議一種聲明你的層次結構的替代方法。

template<class PointT> 
class A 
{ 
public: 
    A() {}; 

    struct model_stuct 
    { 
     // need something to use in comparison, so i just threw this in. 
     int value; 
    }; 
}; 

// comparitor 
template<class PointT> 
bool compareLines(
    const typename A<PointT>::model_stuct& left, 
    const typename A<PointT>::model_stuct& right) 
{ 
    return left.value < right.value; 
} 

template<class PointT> 
class B 
{ 
public: 
    B() : lines() {}; 

    void sort() 
    { 
     std::sort(lines.begin(), lines.end(), compareLines<PointT>); 
    } 

    std::vector<typename A<PointT>::model_stuct> lines; 
}; 


// main entrypoint 
int main(int argc, char *argv[]) 
{ 
    // this does nothing, but demonstrate that it can compile and 
    // sort() doesn't puke. 
    B<int> bInt; 
    bInt.sort(); 
    return 0; 
} 
+0

+1因爲有唯一的答案來解決缺少的'typename's。 [在線演示](http://liveworkspace.org/code/07d72908e0f017fe5c8c3b55c8a2a9f9) – ildjarn