【发布时间】:2015-07-01 22:45:50
【问题描述】:
我有两个函数 foo 的重载,它们采用不同的 std::functions,当与 std::bind 的结果一起使用时,这会导致后者出现歧义问题。我不明白为什么只有这是模棱两可的。
void foo(std::function<void(int)>) {}
void foo(std::function<int()>) {}
void take_int(int) { }
int ret_int() { return 0; }
将int() 与bind 函数一起使用时,出现歧义错误
foo(std::bind(ret_int)); // ERROR
出现 gcc-5.1 错误(与 clang 类似)
error: call to 'foo' is ambiguous
foo(std::bind(ret_int));
^~~
note: candidate function
void foo(std::function<void(int)>) {}
^
note: candidate function
void foo(std::function<int()>) {}
但是以下所有的工作
foo(std::bind(take_int, _1));
foo(take_int);
foo(ret_int);
foo([](){ return ret_int(); });
struct TakeInt {
void operator()(int) const { }
};
struct RetInt {
int operator()() const { return 0; }
};
foo(TakeInt{});
foo(RetInt{});
查看std::function构造函数
template< class F >
function( F f );
对我来说,在不同std::function 类型上具有多个重载的任何函数都应该有歧义,但这只是绑定调用的问题。然后我想“也许在处理函数类型和 lambdas 时发生了一些神奇的事情,它不处理实际的类”,但它也处理了这些。
在 en.cppreference 上有一个注释,上面写着 [since c++14]
除非 f 对于参数类型 Args... 和返回类型 R 是 Callable 的,否则此构造函数不参与重载决议
【问题讨论】:
标签: c++ overloading c++14 std-function stdbind