Skip to content

Instantly share code, notes, and snippets.

@artivis
Created May 20, 2020 23:57
Show Gist options
  • Save artivis/74da827f95fc48da36f12a7923f4436a to your computer and use it in GitHub Desktop.
Save artivis/74da827f95fc48da36f12a7923f4436a to your computer and use it in GitHub Desktop.
some crtp base class #cpp #c++ #crtp
#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