Skip to content

Commit

Permalink
core: Add crtp helper class.
Browse files Browse the repository at this point in the history
  • Loading branch information
xlauko committed Jul 2, 2024
1 parent 0801d16 commit 0439d34
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions core/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ add_headers(core GAP_CORE_HEADERS
concepts.hpp
config.hpp
coroutine.hpp
crtp.hpp
dense_map.hpp
generator.hpp
hash.hpp
Expand Down
20 changes: 20 additions & 0 deletions core/include/gap/core/crtp.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright (c) 2024, Trail of Bits, Inc.

#pragma once

namespace gap::core {

template< typename T, template< typename > class crtp_type >
struct crtp
{
T &underlying() { return static_cast< T & >(*this); }

const T &underlying() const { return static_cast< const T & >(*this); }

private:
crtp() {}

friend crtp_type< T >;
};

} // namespace gap::core
1 change: 1 addition & 0 deletions test/core/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
add_gap_test(test-gap-core
bigint.cpp
benchmark.cpp
crtp.cpp
dense_map.cpp
hash.cpp
memoize.cpp
Expand Down
25 changes: 25 additions & 0 deletions test/core/crtp.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Copyright (c) 2022-present, Trail of Bits, Inc.

#include <array>
#include <doctest/doctest.h>
#include <gap/core/crtp.hpp>

namespace gap::test
{
template< typename derived >
struct base : gap::core::crtp< derived, base > {
using gap::core::crtp< derived, base >::underlying;

int foo() { return underlying().bar(); }
};

struct derived : base< derived > {
int bar() { return 10; }
};

TEST_CASE("CRTP test") {
derived d;
CHECK(d.foo() == 10);
}

} // namespace gap::test

0 comments on commit 0439d34

Please sign in to comment.