【发布时间】:2014-07-17 11:33:41
【问题描述】:
如果 lambda 的返回类型不匹配,我的 clang 编译器 (3.3) 似乎不会产生任何错误:
#include <functional>
typedef std::function<void()> 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 <functional>
struct A {};
struct B {};
typedef std::function<A()> 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 '<lambda at foo2.cpp:16:6>' to 'aFunc' (aka 'function<A ()>') for 1st argument
void foo(aFunc func)
^
1 error generated.
【问题讨论】:
-
查看
std::function的文档。这里没有错误是设计使然。 -
@SebastianPhilipp 如果你有 Haskell 背景,
std::function<b(a)>不是a -> b。不要做这样的假设。 -
@R.MartinhoFernandes:为什么不呢?
-
@LightnessRacesinOrbit 返回值的函数可以在不返回值的函数的任何地方使用。它是返回类型协方差。
标签: c++ c++11 types lambda clang