TGViewer
C++ - Reddit C++ - Reddit @r_cpp · 229 subscribers
Post #24358 17
Enhancing strict types with generic mixins

I was playing around with strict types today, and realized you could enhance strict types very easily and pull operators you want. I don't know if this is already a popular pattern or not, but when I got to it felt really cool!

// Standard generic "strict type" wrapper
template <typename T, typename Derived>
struct Strict {
constexpr explicit Strict(T value)
: mValue { value }
{}


static Derived Make(T value) {
return Derived{Strict<T, Derived>{value}};
}

T mValue;
};


template <typename T>
struct Spaceship {
constexpr auto operator<=>(const Spaceship& other) const noexcept {
return static_cast<const T&>(*this).mValue <=> static_cast<const T&>(other).mValue;
}
};


template <typename T>
struct StreamOut {
friend std::ostream& operator<< (std::ostream& stream, const StreamOut<T>& streamOut) {
stream << static_cast<const T&>(streamOut).mValue;
return stream;
}
};


template <typename T>
struct Mult {
constexpr auto operator*(const Mult& other) const noexcept {
return T::Make(static_cast<const T&>(*this).mValue * static_cast<const T&>(other).mValue);
}
};


// We can inherit and add traits we need!! :)
struct MyType: Strict<int, MyType>, Spaceship<MyType>, Mult<MyType>, StreamOut<MyType>
{};


int main() {
auto x = MyType::Make(4);
auto y = MyType::Make(9);


std::cout << std::boolalpha << (x <= y) << std::endl;
std::cout << x * y << std::endl;
}

[https://godbolt.org/z/rT84qox36](https://godbolt.org/z/rT84qox36)

https://redd.it/1p7fwv0
@r_cpp
godbolt.org Compiler Explorer - C++ (x86-64 gcc 15.2) template <typename T, typename Derived> struct Strict { constexpr explicit Strict(T value) : mValue { value } {} static Derived Make(T value) { return Derived(Strict<T, Derived>{value}); } T mValue; }; template <typename…
More from @r_cpp
  1. Oct 11, 2026wxWidgets 3.2.12 and 3.3.4 Released https://wxwidgets.org/news/2026/10/wxwidgets-3.2.12-an…
  2. Oct 11, 2026VKRT NES Remaster — an open-source C++20 NES emulator with an observation-driven remasteri…
  3. Oct 11, 2026Right way to test async code https://redd.it/1x2wqgz @r_cpp
  4. Oct 10, 2026Yantra: an LALR(1) parser generator for C++23 Yantra: an LALR(1) parser generator for C++2…
  5. Oct 10, 2026Opting in, and back out again https://dryperspective.github.io/posts/opting-in/ https://re…
  6. Oct 10, 2026I’m Building Bursztyn OS a Polish Operating System From Scratch I’m building Bursztyn OS,…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →