Last active
September 24, 2019 16:35
-
-
Save npetrenko/4834b88ed17844e007ff7daa172ede5f to your computer and use it in GitHub Desktop.
Using concepts for matching CRTP inheritance
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 Derived> | |
class Base { | |
public: | |
int Create() const { | |
return static_cast<const Derived&>(*this).CreateImpl(); | |
} | |
}; | |
class Derived : public Base<Derived> { | |
friend Base<Derived>; | |
int CreateImpl () const { | |
return 0; | |
} | |
}; | |
template <class Derived, template <class...> class BaseTemplate> | |
struct IsTemplateBase { | |
template <class... T> | |
static std::true_type tester(BaseTemplate<T...>*); | |
static std::false_type tester(...); | |
static constexpr bool value | |
= decltype(tester(std::declval<Derived*>()))::value; | |
}; | |
template <class T, template <class...> class BaseTemplate> | |
concept AbstractBaseConcept = IsTemplateBase<T, BaseTemplate>::value; | |
template <class T> | |
concept BaseConcept = AbstractBaseConcept<T, Base>; | |
template <BaseConcept T> | |
int GetValue(const T& obj) { | |
return obj.Create(); | |
} | |
int main () { | |
Derived d; | |
return GetValue(d); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment