Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@ enable_testing()
find_package(GTest REQUIRED)

add_subdirectory(cpp20_modules)
add_subdirectory(cpp20_concepts)
2 changes: 2 additions & 0 deletions cpp20_concepts/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
add_subdirectory(lib)
add_subdirectory(test)
8 changes: 8 additions & 0 deletions cpp20_concepts/lib/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
set(TARGET concept_lib)
add_library(${TARGET})
set_target_properties(${TARGET} PROPERTIES LINKER_LANGUAGE CXX)

set(SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/include/hashable.h)

target_sources(${TARGET} PUBLIC ${SOURCES})
target_include_directories(${TARGET} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
14 changes: 14 additions & 0 deletions cpp20_concepts/lib/include/hashable.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Declaration of the concept "Hashable", which is satisfied by any type 'T'
// such that for values 'a' of type 'T', the expression std::hash<T>{}(a)
// compiles and its result is convertible to std::size_t
#include <functional>

template <typename T>
concept Hashable = requires(T a)
{
{
std::hash<T>{}(a)
} -> std::convertible_to<std::size_t>;
};

// https://en.cppreference.com/w/cpp/language/constraints
7 changes: 7 additions & 0 deletions cpp20_concepts/test/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
set(TARGET concept_tests)

add_executable(${TARGET})
target_sources(${TARGET} PRIVATE tests.cpp)
target_link_libraries(${TARGET} PRIVATE concept_lib GTest::gtest
GTest::gtest_main)
add_test(NAME ${TARGET} COMMAND ${TARGET})
25 changes: 25 additions & 0 deletions cpp20_concepts/test/tests.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#include <gtest/gtest.h>

#include <hashable.h>

struct meow
{
};

// Constrained C++20 function template:
template <Hashable T>
T hashable_func1(T t) { return t; }

// Alternative ways to apply the same constraint:
template <typename T>
requires Hashable<T>
T hashable_func2(T t) { return t; }

template <typename T>
T hashable_func3(T t) requires Hashable<T> { return t; }

int main()
{
auto const result = hashable_func1(1) + hashable_func2(2) + hashable_func3(3);
return !(6ULL == result);
}