#include <catch2/catch_test_macros.hpp>
#include <map>
#include <mutex>
#include <string>
using namespace anyxx;
namespace {
struct widget_a {
[[nodiscard]]std::string get() const { return "widget_a"; }
};
ANY(widget, (
ANY_FN(std::string, get, (),
const)), )
any_widget<weak> any_widget_weak;
void observe(int expected_use_count) {
auto s = std::make_shared<int>(1);
std::weak_ptr<int> w = s;
CHECK(get_proxy(any_widget_weak).use_count() == expected_use_count);
auto any_widget_shared_const =
lock(any_widget_weak);
if (expected_use_count > 0)
CHECK(any_widget_shared_const);
else
CHECK(!any_widget_shared_const);
}
}
TEST_CASE("example X1/ weak cppreference") {
{
auto any_widget_shared_const =
any_widget<shared>{std::make_shared<widget_a>()};
static_assert(borrowable_from<weak, shared, any_widget<shared>::v_table_t>);
any_widget_weak = any_widget_shared_const;
observe(1);
}
observe(0);
}
namespace {
any_widget<shared> load_widget([[maybe_unused]] int id) {
return std::make_shared<widget_a>();
}
static std::map<int, any_widget<weak>> cache;
static std::mutex cache_mutex;
any_widget<shared> make_widget(int id) {
std::lock_guard hold{cache_mutex};
return *
lock(cache[
id]).or_else(
[&] -> std::optional<any_widget<shared>> {
auto s = load_widget(id);
cache[id] = s;
return s;
});
}
}
TEST_CASE("example X1/ sutters favorite 10 cpp lines") {
{
auto w1 = make_widget(0);
CHECK(w1.get() == "widget_a");
CHECK(get_proxy(w1).use_count() == 1);
CHECK(cache.size() == 1);
CHECK(get_proxy(cache[0]).use_count() == 1);
{
auto w2 = make_widget(0);
CHECK(w2.get() == "widget_a");
CHECK(get_proxy(w2).use_count() == 2);
CHECK(cache.size() == 1);
CHECK(get_proxy(cache[0]).use_count() == 2);
}
CHECK(get_proxy(w1).use_count() == 1);
CHECK(cache.size() == 1);
CHECK(get_proxy(cache[0]).use_count() == 1);
}
CHECK(get_proxy(cache[0]).use_count() == 0);
}
C++ header only library for external polymorphism.
auto lock(FromAny const &from_interface)
Lock a shared any.
Definition anyxx.hpp:3490
#define ANY_FN(ret, name, params, const_)
TRAIT function whose default behavior is to call an equally named member function of the model.
Definition anyxx.hpp:1019
#define ANY(n, l,...)
Simple ANY macro.
Definition anyxx.hpp:884