Created
October 12, 2018 10:32
-
-
Save gatchamix/ef6c46f547abe9b355b5b3da04509f66 to your computer and use it in GitHub Desktop.
simulating features of dynamic polymorphism and class inheritance at compile-time
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> | |
// | |
template <class...> | |
struct type_pack | |
{}; | |
// | |
namespace detail | |
{ | |
template <class R, class T> | |
auto constexpr match(R T::*) | |
-> std::true_type; | |
template <class...> | |
auto constexpr match(...) | |
-> std::false_type; | |
} | |
#define has_member_function(...) \ | |
[] \ | |
{ \ | |
using type = __VA_ARGS__; \ | |
HAS_MEMBER_FUNCTION_IMPL_1 | |
#define HAS_MEMBER_FUNCTION_IMPL_1(...) \ | |
auto constexpr helper = [] \ | |
<class __T, class... __Sig> \ | |
(type_pack<__T, __Sig...>) \ | |
-> decltype(detail::match<__Sig...>(&__T::__VA_ARGS__)) \ | |
{}; \ | |
HAS_MEMBER_FUNCTION_IMPL_2 | |
#define HAS_MEMBER_FUNCTION_IMPL_2(...) \ | |
using input = type_pack<type __VA_OPT__(, __VA_ARGS__)>; \ | |
return std::is_invocable_r_v<std::true_type, decltype(helper), input>; \ | |
}() | |
// check for existance of member functions | |
// | |
// usage: | |
// has_member_function(T[<Ts...>])([template] name[<Us...>])([signature]) | |
// where 'signature' is: | |
// R([Args...]) [const] [volatile] | |
// | |
// CRTP base class | |
template <class T> | |
struct foo | |
: T | |
{ | |
// simulated deleted / final virtual function | |
static_assert(!has_member_function(T)(deleted_function)()); | |
// simulated pure virtual function | |
static_assert(has_member_function(T)(pure_virtual_function)(int() const)); | |
// simulated virtual function | |
auto constexpr virtual_function() const | |
{ | |
if constexpr (has_member_function(T)(virtual_function)(int() const)) | |
{ return T::virtual_function(); } | |
else | |
{ return 0; } | |
} | |
// calling functions in simulated derived class | |
auto constexpr func() const | |
{ return T::pure_virtual_function(); } | |
}; | |
// CRTP derived class | |
struct bar | |
{ | |
auto constexpr virtual_function() const | |
{ return 1; } | |
auto constexpr pure_virtual_function() const | |
{ return 2; } | |
}; | |
// | |
auto main() | |
-> int | |
{ | |
auto constexpr test = foo<bar>{}; | |
return test.virtual_function() + test.func(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment