为什么此重载函数调用不明确? [英] Why is this call of overloaded function ambiguous?
问题描述
为什么此构造函数调用不明确?
Why is this constructor call ambiguous?
#include <functional>
class A {
std::function<int(void)> f_;
std::function<float(void)> g_;
public:
A(std::function<int(void)> f) { f_ = f; }
A(std::function<float(void)> g) { g_ = g; }
~A() {}
};
int main()
{
A a([](){ return (int)1; });
return 0;
}
请注意打字。
有没有办法告诉编译器使用哪个构造函数重载?
Is there a way to tell the compiler which constructor overload to use?
推荐答案
因为要传递的内容没有匹配类型,以便我们进入转换序列以查找要使用的重载。可以从返回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); }
这篇关于为什么此重载函数调用不明确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!