参见英文答案 >
Using `std::function` to call non-void function 3个
看起来我的clang编译器(3.3)不会产生任何错误,如果lambda的返回类型不匹配:
#include
typedef std::function voidFunc;
void foo(voidFunc func)
{
func();
}
int main()
{
int i = 42;
foo([i]()
{
return i;
});
return 0;
}
编译此代码不会显示任何错误:
clang++ -c -Xclang -stdlib=libc++ -std=c++11 -Weverything -Wno-c++98-compat -Wno-missing-prototypes -o foo.o foo.cpp
如何为此类问题生成类型错误?
编辑:
这会生成类型错误:
#include
struct A {};
struct B {};
typedef std::function aFunc;
void foo(aFunc func)
{
func();
}
int main()
{
int i = 42;
foo([i]()
{
return B();
});
return 0;
}
这是错误:
foo2.cpp:16:2: error: no matching function for call to 'foo'
foo([i]() {
^~~
foo2.cpp:8:6: note: candidate function not viable: no known conversion from '' to 'aFunc' (aka 'function') for 1st argument
void foo(aFunc func)
^
1 error generated.