c ++如何将几个重载函数之一指定为模板函数中的参数

c++ How do you specify one of several overloaded functions as an argument in a template Function

我想使用一些预定义的比较器作为模板函数的参数。

代码框架:

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 update 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&));

但这也是不允许的...

如何解决这个问题? (我知道我可以求助于 lambda,但还有其他方法吗?)

明确指定模板参数类型,如下所示:

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