lmi-commits
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[lmi-commits] [lmi] odd/shared_ref 770bcc0: Sketch for shared_ref, with


From: Greg Chicares
Subject: [lmi-commits] [lmi] odd/shared_ref 770bcc0: Sketch for shared_ref, with unit test
Date: Fri, 5 Feb 2021 12:01:02 -0500 (EST)

branch: odd/shared_ref
commit 770bcc0e77084dcf019483d6e600af709bb301de
Author: Gregory W. Chicares <gchicares@sbcglobal.net>
Commit: Gregory W. Chicares <gchicares@sbcglobal.net>

    Sketch for shared_ref, with unit test
    
    As long as '.' cannot be overloaded, it looks like there's no
    transparent way to make natural 'object.something' syntax work.
    The unit test demonstrates that operator()() can be used, so
    'object().something' works; but the same convenience can be had
    by writing
      std::shared_ptr<Foo> foo_;
      Foo& foo() const {return *foo_;}
      foo().something;
    so this sketch seems pretty useless.
---
 sandbox_test.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 42 insertions(+)

diff --git a/sandbox_test.cpp b/sandbox_test.cpp
index 549512b..2a598e8 100644
--- a/sandbox_test.cpp
+++ b/sandbox_test.cpp
@@ -23,7 +23,49 @@
 
 #include "test_tools.hpp"
 
+#include <memory>
+
+class X
+{
+  public:
+    void x(int i) {x_ = i; x();}
+    int x() const {return x_;}
+
+  private:
+    int x_ = {};
+};
+
+template<typename T>
+class shared_ref
+{
+  public:
+//  shared_ref(std::shared_ptr<T> const&  p) : p_ {p} {}
+//  shared_ref(std::shared_ptr<T> const&& p) : p_ {std::move(p)} {}
+    shared_ref(std::shared_ptr<T> p) : p_ {p} {if(!p) throw "null!";}
+
+    operator T      &  () const {return *p_;}
+    T&       operator()() const {return *p_;}
+//  T const& operator()() const {return *p_;}
+//  operator T const&  () const {return *p_;} // not useful?
+
+  private:
+    std::shared_ptr<T> p_;
+};
+
 int test_main(int, char*[])
 {
+    auto xp = std::make_shared<X>();
+    shared_ref<X> xr = {xp};
+
+    std::cout << "xp->x() is " << xp->x() << std::endl;
+    xr().x(3);
+    std::cout << "xp->x() is " << xp->x() << std::endl;
+    std::cout << "xr().x() is " << xr().x() << std::endl;
+
+    xp->x(5);
+    std::cout << "xp->x() is " << xp->x() << std::endl;
+    std::cout << "xr().x() is " << xr().x() << std::endl;
+//  xr.x(); // operator T&() doesn't enable this syntax
+
     return 0;
 }



reply via email to

[Prev in Thread] Current Thread [Next in Thread]