Last active
July 10, 2021 16:57
-
-
Save vladiant/27b27dd0c72fdc4e54ef8d38987f3087 to your computer and use it in GitHub Desktop.
C++ Concept Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template<typename T, typename=void> | |
struct has_release : std::false_type {}; | |
template<typename T> | |
struct has_release<T, decltype(std::declval<T>().Release())> : std::true_type {}; | |
template<typename T> | |
class Wrapper { | |
T mData; | |
public: | |
~Wrapper() { | |
if constexpr(has_release<T>::value) { mData.Release(); } | |
} | |
}; | |
// C++20 Templates - the Next Level: Concepts and More - Andreas Fertig [ ACCU 2021 ] | |
// https://www.youtube.com/watch?v=ZGPz4hoBPck | |
// https://andreasfertig.info/ | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <type_traits> | |
#include <concepts> | |
#include <iostream> | |
template <typename T> | |
constexpr bool critical_code_v() { return false;}; | |
struct critical_code_semantics_tag {}; | |
template <typename T> requires std::is_base_of_v<critical_code_semantics_tag,T> | |
constexpr bool critical_code_v() { return true;}; | |
template<typename T> | |
concept critical_code = critical_code_v<T>(); | |
template<typename T> | |
struct mark_critical : public T, public critical_code_semantics_tag { | |
using T::operator(); | |
}; | |
//deduction guide | |
template<typename T> mark_critical(T) -> mark_critical<T>; | |
template<critical_code Alert> | |
void run_with_priviliges(const std::string& msg, Alert alert) { | |
alert(msg); | |
} | |
int main() { | |
run_with_priviliges("hello world", mark_critical{[](const auto& msg) { std::cout << msg << std::endl;}}); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment