2016-11-16 23 views
2

テンプレート関数の引数としていくつかの定義済みコンパレータを使いたいと思います。C++いくつかのオーバーロードされた関数の1つをテンプレートの引数としてどのように指定するのですか?関数

コードスケルトン:しかし

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' 

明らかにコンパイルし、次のエラーが発生します、like

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

しかし、これも許可されていません。

これを解決するにはどうすればよいですか? (私は、ラムダに頼ることができます知っているが、別の方法は何ですか?)

答えて

1

はこのように、明示的にテンプレートパラメータの種類を指定します。

auto result = calculateSomething<bool(const Line&,const Line&)>(customCompare); 
関連する問題