2016-11-16 21 views
2

我想使用一些預定義的比較器作爲模板函數的參數。C++如何指定幾個重載函數之一作爲模板中的參數函數

代碼框架:

struct Line 
{ 
    double length() const; 
    // some data 
}; 

struct Square 
{ 
    double area() const; 
    // some data 
}; 

bool customCompare(const Line& a1, const Line& a2) { return a1.length() < a2.length(); } 
bool customCompare(const Square& b1, const Square& b2) { return b1.area() < b2.area(); } 

template <typename Comparator> 
double calculateSomething(Comparator&& tieBreaker) 
{ 
    Line l1, l2; 
    return tiebreaker(l1, l2) ? l1.length() : l2.length(); 
} 

auto result = calculateSomething(customCompare); 

然而,我的編譯器(VS12更新5)給出了下面的編譯錯誤

error C2914: 'calculateSomething' : cannot deduce template argument as function argument is ambiguous 
error C2784: 'double calculateSomething(Comparator &&)' : could not deduce template argument for 'overloaded function type' from 'overloaded function type' 

很顯然,我想要做的是更準確地指定的比較,就像

auto result = calculateSomething(customCompare(const Line&, const Line&)); 

但是這也是不允許的......

如何解決這個問題? (我知道我可以再打一個拉姆達,但有另一種方式?)

回答

1

明確指定模板參數類型,就像這樣:

auto result = calculateSomething<bool(const Line&,const Line&)>(customCompare); 
相關問題