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