[PATCH] D88901: [ADT] function_ref's constructor is unavailable if the argument is not callable.

Sam McCall via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Tue Oct 6 07:37:12 PDT 2020


sammccall created this revision.
sammccall added a reviewer: kadircet.
Herald added subscribers: llvm-commits, dexonsmith.
Herald added a project: LLVM.
sammccall requested review of this revision.

This allows overload sets containing function_ref arguments to work correctly
Otherwise they're ambiguous as anything "could be" converted to a function_ref.

This matches proposed std::function_ref, absl::function_ref, etc.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D88901

Files:
  llvm/include/llvm/ADT/STLExtras.h
  llvm/unittests/ADT/FunctionRefTest.cpp


Index: llvm/unittests/ADT/FunctionRefTest.cpp
===================================================================
--- llvm/unittests/ADT/FunctionRefTest.cpp
+++ llvm/unittests/ADT/FunctionRefTest.cpp
@@ -48,4 +48,15 @@
   ASSERT_EQ(1, X());
 }
 
+// Test that overloads on function_refs are resolved as expected.
+const char *returns(StringRef) { return "not a function"; }
+const char *returns(function_ref<double()> F) { return "number"; }
+const char *returns(function_ref<StringRef()> F) { return "string"; }
+
+TEST(FunctionRefTest, SFINAE) {
+  EXPECT_EQ("not a function", returns("boo!"));
+  EXPECT_EQ("number", returns([] { return 42; }));
+  EXPECT_EQ("string", returns([] { return "hello"; }));
+}
+
 } // namespace
Index: llvm/include/llvm/ADT/STLExtras.h
===================================================================
--- llvm/include/llvm/ADT/STLExtras.h
+++ llvm/include/llvm/ADT/STLExtras.h
@@ -190,9 +190,17 @@
   function_ref() = default;
   function_ref(std::nullptr_t) {}
 
-  template <typename Callable>
+  template <typename Callable,
+            // Only allow this constructor if the object is actually callable
+            // and returns the correct type.
+            typename = typename std::enable_if<
+                std::is_void<Ret>::value ||
+                std::is_convertible<
+                    typename std::result_of<Callable(Params...)>::type,
+                    Ret>::value>::type>
   function_ref(
       Callable &&callable,
+      // This is not a copy-constructor.
       std::enable_if_t<
           !std::is_same<std::remove_cv_t<std::remove_reference_t<Callable>>,
                         function_ref>::value> * = nullptr)


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D88901.296460.patch
Type: text/x-patch
Size: 1684 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20201006/152ba291/attachment.bin>


More information about the llvm-commits mailing list