为什么编译器不能选择最明显的重载:
#include <iostream>
#include <functional>
static void foo(const std::function<void(bool)>& f) {
std::cerr << "using bool overload" << std::endl;
f(true);
}
static void foo(const std::function<void(int)>& f) {
std::cerr << "using int overload" << std::endl;
f(1);
}
int main() {
foo([](const bool value) {
std::cout << std::boolalpha << value << std::endl;
});
foo([](const int value) {
std::cout << value << std::endl;
});
return 0;
}
你会期望输出:
using bool overload
true
using int overload
1
但是,编译器无法推断出正确的重载:
gcc-4.8
:
main.cpp: In function 'int main()':
main.cpp:17:6: error: call of overloaded 'foo(main()::__lambda0)' is ambiguous
});
^
main.cpp:17:6: note: candidates are:
main.cpp:4:13: note: void foo(const std::function<void(bool)>&)
static void foo(const std::function<void(bool)>& f) {
^
main.cpp:9:13: note: void foo(const std::function<void(int)>&)
static void foo(const std::function<void(int)>& f) {
^
clang-3.4
:
main.cpp:15:5: error: call to 'foo' is ambiguous
foo([](const bool value) {
^~~
main.cpp:4:13: note: candidate function
static void foo(const std::function<void(bool)>& f) {
^
main.cpp:9:13: note: candidate function
static void foo(const std::function<void(int)>& f) {
^
是不是因为std::function
构造函数会自动消费和转换参数?