Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add explicit conversion to bool in ThreadSafeFunctor #65

Open
jdv85 opened this issue Dec 3, 2024 · 0 comments
Open

Add explicit conversion to bool in ThreadSafeFunctor #65

jdv85 opened this issue Dec 3, 2024 · 0 comments

Comments

@jdv85
Copy link

jdv85 commented Dec 3, 2024

In my project, when trying to check if an choc::threading::ThreadSafeFunctor<std::function<void()>> instance holds a value, I get this compiler error:

choc/threading/choc_ThreadSafeFunctor.h:142:12: error: no viable conversion from returned value of type 'std::function<void ()>' to function return type 'bool'
    return callback->fn;
           ^~~~~~~~~~~~

The problem seems to be that std::function marks it conversion to bool as explicit. I can fix the problem by using an explicit conversion in choc:

diff --git a/threading/choc_ThreadSafeFunctor.h b/threading/choc_ThreadSafeFunctor.h
index f58e5d8..2f02f1d 100644
--- a/threading/choc_ThreadSafeFunctor.h
+++ b/threading/choc_ThreadSafeFunctor.h
@@ -139,7 +139,7 @@ template <typename FunctionType>
 ThreadSafeFunctor<FunctionType>::operator bool() const
 {
     std::scoped_lock l (callback->lock);
-    return callback->fn;
+    return (bool)callback->fn;
 }
 
 template <typename FunctionType>

I'm not sure this is the best fix, but it works for me.

Here's a test case that illustrates the use case:

diff --git a/tests/choc_tests.h b/tests/choc_tests.h
index 1dfed39..919d3e6 100644
--- a/tests/choc_tests.h
+++ b/tests/choc_tests.h
@@ -2870,6 +2870,18 @@ inline void testThreading (choc::test::TestProgress& progress)
     {
         CHOC_TEST (ThreadSafeFunctor)
 
+        {
+            choc::threading::ThreadSafeFunctor<std::function<void()>> tsf;
+
+            CHOC_EXPECT_FALSE (tsf);
+            tsf = [] () {  };
+            CHOC_EXPECT_TRUE (tsf);
+
+            tsf.reset();
+            CHOC_EXPECT_FALSE (tsf);
+        }
+
+
         {
             choc::threading::ThreadSafeFunctor<std::function<void(int)>> tsf;

I'm building with Clang from Xcode 15.4.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant