Browse Source

Type constrains for pointer related operations implemented.

main
offa 7 years ago
parent
commit
5508546664
2 changed files with 33 additions and 3 deletions
  1. +16
    -0
      include/unique_resource.h
  2. +17
    -3
      test/UniqueResourceTest.cpp

+ 16
- 0
include/unique_resource.h View File

#pragma once #pragma once


#include <utility> #include <utility>
#include <type_traits>


namespace sr namespace sr
{ {
return m_resource; return m_resource;
} }


template<class R = std::decay_t<Ressource>,
std::enable_if_t<std::is_pointer<R>::value &&
( std::is_class<std::remove_pointer_t<R>>::value
|| std::is_union<std::remove_pointer_t<R>>::value ), int> = 0>
R operator->() const noexcept
{
return m_resource;
}

template<class R = std::decay_t<Ressource>,
std::enable_if_t<std::is_pointer<R>::value, int> = 0>
std::add_lvalue_reference_t<std::remove_pointer_t<Ressource>> operator*() const noexcept
{
return *get();
}


const Deleter& get_deleter() const noexcept const Deleter& get_deleter() const noexcept
{ {

+ 17
- 3
test/UniqueResourceTest.cpp View File

#include <catch.hpp> #include <catch.hpp>


using Handle = int; using Handle = int;
using PtrHandle = std::add_pointer_t<Handle>;


TEST_CASE("deleter called on destruction", "[UniqueResource]") TEST_CASE("deleter called on destruction", "[UniqueResource]")
{ {
REQUIRE(guard.get() == 3); REQUIRE(guard.get() == 3);
} }


TEST_CASE("conversion operator accesses ressource", "[UniqueResource]")
TEST_CASE("conversion operator", "[UniqueResource]")
{ {
auto guard = sr::unique_resource(Handle{3}, [](auto) { }); auto guard = sr::unique_resource(Handle{3}, [](auto) { });
const auto& ref = guard; const auto& ref = guard;
REQUIRE(ref == 3); REQUIRE(ref == 3);
} }


// TODO: conditional access functions
TEST_CASE("pointer access operator" "[UniqueResource]")
{
const auto p = std::make_pair(3, 4);
auto guard = sr::unique_resource(&p, [](auto) { });
const auto x = guard.operator->();
REQUIRE(x->first == 3);
}

TEST_CASE("dereference operator", "[UniqueResource]")
{
Handle h{4};
auto guard = sr::unique_resource(PtrHandle{&h}, [](auto) { });
const auto x = guard.operator*();
REQUIRE(x == 4);
}


TEST_CASE("deleter access", "[UniqueResource]") TEST_CASE("deleter access", "[UniqueResource]")
{ {
REQUIRE(value == 0); REQUIRE(value == 0);
guard.get_deleter()(6); guard.get_deleter()(6);
REQUIRE(value == 6); REQUIRE(value == 6);

} }

Loading…
Cancel
Save