Make FunctionRef support bool operator
authorBi Xue <bixue@fb.com>
Thu, 29 Dec 2016 06:18:32 +0000 (22:18 -0800)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Thu, 29 Dec 2016 06:33:23 +0000 (22:33 -0800)
Summary:
To support following code:
```
void foo(folly::FunctionRef<void(void)> callback = {}) {
  if (callback) {
    callback();
  }
}
```

Reviewed By: yfeldblum

Differential Revision: D4372296

fbshipit-source-id: 7d21e6a44b6f6b046b424f0139465511dbae7b8b

folly/Function.h
folly/test/FunctionRefTest.cpp

index d6fb29f6010b16735b52ebfd8254e365a1e87f3c..de51c324ce6a6988343ffc922479ce7ccb5a8572 100644 (file)
@@ -780,6 +780,10 @@ class FunctionRef<ReturnType(Args...)> final {
   ReturnType operator()(Args... args) const {
     return call_(object_, static_cast<Args&&>(args)...);
   }
+
+  explicit operator bool() const {
+    return object_;
+  }
 };
 
 } // namespace folly
index 621b0ad8205b519d6c8c7ab859076c7170dc4404..02bb213dab06820362afad82fe3e4837733f4d3a 100644 (file)
@@ -137,11 +137,13 @@ TEST(FunctionRef, OverloadedFunctor) {
 TEST(FunctionRef, DefaultConstructAndAssign) {
   FunctionRef<int(int, int)> 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));
 }