CRTP
Curiously recurring template pattern
Назначение
Решаемые задачи
Пример реализации идиомы CRTP
template <class derived>
struct compare {};
struct value : compare<value>
{
int m_x;
value(int x) : m_x(x) {}
bool operator<(const value &rhs) const
{
return m_x < rhs.m_x;
}
};
template <class derived>
bool operator > (const compare<derived> &lhs, const compare<derived> &rhs)
{
// static_assert(std::is_base_of_v<compare<derived>, derived>); // Безопасность времени компиляции
return (static_cast<const derived&>(rhs) < static_cast<const derived&>(lhs));
}
int main()
{
value v1{5}, v2{10};
cout << boolalpha << "v1 > v2: " << (v1 > v2) << '\n';
return 0;
}Last updated