From: Bi Xue Date: Thu, 29 Dec 2016 06:18:32 +0000 (-0800) Subject: Make FunctionRef support bool operator X-Git-Tag: v2017.03.06.00~153 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=42f55fa585897da3f9b3afefc399a4544bbaf074;p=folly.git Make FunctionRef support bool operator Summary: To support following code: ``` void foo(folly::FunctionRef callback = {}) { if (callback) { callback(); } } ``` Reviewed By: yfeldblum Differential Revision: D4372296 fbshipit-source-id: 7d21e6a44b6f6b046b424f0139465511dbae7b8b --- diff --git a/folly/Function.h b/folly/Function.h index d6fb29f6..de51c324 100644 --- a/folly/Function.h +++ b/folly/Function.h @@ -780,6 +780,10 @@ class FunctionRef final { ReturnType operator()(Args... args) const { return call_(object_, static_cast(args)...); } + + explicit operator bool() const { + return object_; + } }; } // namespace folly diff --git a/folly/test/FunctionRefTest.cpp b/folly/test/FunctionRefTest.cpp index 621b0ad8..02bb213d 100644 --- a/folly/test/FunctionRefTest.cpp +++ b/folly/test/FunctionRefTest.cpp @@ -137,11 +137,13 @@ TEST(FunctionRef, OverloadedFunctor) { TEST(FunctionRef, DefaultConstructAndAssign) { FunctionRef fref; + EXPECT_FALSE(fref); EXPECT_THROW(fref(1, 2), std::bad_function_call); int (*func)(int, int) = [](int x, int y) { return 10 * x + y; }; fref = func; + EXPECT_TRUE(fref); EXPECT_EQ(42, fref(4, 2)); }