瀏覽代碼

Type constrains for pointer related operations implemented.

main
offa 7 年之前
父節點
當前提交
5508546664
共有 2 個檔案被更改,包括 33 行新增3 行删除
  1. +16
    -0
      include/unique_resource.h
  2. +17
    -3
      test/UniqueResourceTest.cpp

+ 16
- 0
include/unique_resource.h 查看文件

@@ -21,6 +21,7 @@
#pragma once

#include <utility>
#include <type_traits>

namespace sr
{
@@ -90,6 +91,21 @@ namespace sr
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
{

+ 17
- 3
test/UniqueResourceTest.cpp 查看文件

@@ -23,6 +23,7 @@
#include <catch.hpp>

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

TEST_CASE("deleter called on destruction", "[UniqueResource]")
{
@@ -249,14 +250,28 @@ TEST_CASE("get accesses ressource", "[UniqueResource]")
REQUIRE(guard.get() == 3);
}

TEST_CASE("conversion operator accesses ressource", "[UniqueResource]")
TEST_CASE("conversion operator", "[UniqueResource]")
{
auto guard = sr::unique_resource(Handle{3}, [](auto) { });
const auto& ref = guard;
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]")
{
@@ -265,5 +280,4 @@ TEST_CASE("deleter access", "[UniqueResource]")
REQUIRE(value == 0);
guard.get_deleter()(6);
REQUIRE(value == 6);

}

Loading…
取消
儲存