lambda表达式是一个类型的类别,而不是一种类型。
我们可以这样做:
struct null_callable_t{
template<class...Ts>
constexpr void operator()(Ts&&...)const{}
explicit constexpr operator bool()const{return false;}
constexpr null_callable_t() {}
friend constexpr bool operator==(::std::nullptr_t, null_callable_t){ return true; }
friend constexpr bool operator==(null_callable_t, ::std::nullptr_t){ return true; }
friend constexpr bool operator!=(::std::nullptr_t, null_callable_t){ return false; }
friend constexpr bool operator!=(null_callable_t, ::std::nullptr_t){ return false; }
};
constexpr null_callable_t null_callable{};
现在我们的代码变成:
template <typename Lambda>
int foo(Lambda bar) {
if(!bar)
return -1;
else
return bar(3);
}
这是非常漂亮:
std::cout << foo([](int a) {return a + 3;}) << std::endl;
std::cout << foo(null_callable) << std::endl;
你所说的 “空拉姆达” 是什么意思? – melpomene
你可以使用'std :: optional'或其他库中的等价物吗? – KABoissonneault