且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么此重载函数调用不明确?

更新时间:2022-12-14 21:50:00

因为要传递的内容没有匹配类型,以便我们进入转换序列以查找要使用的重载。可以从返回int的lambda对象隐式创建函数的两个版本。因此,编译器无法决定选择创建哪个。尽管从直观上看,C ++中的规则不允许这样做。

Because what you are passing doesn't match the types so we enter into conversion sequences to find the overload to use. Both versions of function can be implicitly created from a lambda object that returns int. Thus the compiler can't decide which to choose to create; though it seems intuitively obvious the rules in C++ don't allow for it.

编辑:

已取消袖口,但我认为这可以解决问题:

Written off the cuff but I think this could do the trick:

template < typename Fun >
typename std::enable_if<std::is_same<typename std::result_of<Fun()>::type, int>::value>::type f(Fun f) ...


template < typename Fun >
typename std::enable_if<std::is_same<typename std::result_of<Fun()>::type, double>::value>::type f(Fun f) ...

等...或者您可以使用标记分派:

etc... Or you might use tag dispatching:

template < typename Fun, typename Tag >
struct caller;

template < typename T > tag {};

template < typename Fun >
struct caller<Fun, tag<int>> { static void call(Fun f) { f(); } };

// etc...

template < typename Fun >
void f(Fun fun) { caller<Fun, typename std::result_of<Fun()>>::call(fun); }