Created
May 20, 2020 23:57
-
-
Save artivis/74da827f95fc48da36f12a7923f4436a to your computer and use it in GitHub Desktop.
some crtp base class #cpp #c++ #crtp
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 <utility> | |
template <typename Derived> | |
struct Crtp { | |
protected: | |
inline Derived& derived() & noexcept { | |
return *static_cast< Derived* >(this); | |
} | |
inline const Derived& derived() const & noexcept { | |
return *static_cast< const Derived* >(this); | |
} | |
inline Derived&& derived() && noexcept { | |
return std::move(*static_cast< Derived* >(this)); | |
} | |
}; | |
struct Foo : Crtp<Foo> | |
{ | |
using Crtp<Foo>::derived; | |
}; | |
int main() { | |
Foo foo_a; | |
const Foo foo_b; | |
static_assert(std::is_same<Foo&, decltype(foo_a.derived())>::value, "nop"); | |
static_assert(std::is_same<const Foo&, decltype(foo_b.derived())>::value, "nop"); | |
static_assert(std::is_same<Foo&&, decltype(Foo().derived())>::value, "nop"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment