Last active
December 10, 2025 02:44
-
-
Save unrays/a370a9e7e33061aebfa04e7fb84baab1 to your computer and use it in GitHub Desktop.
An elegant and conceptually interesting CRTP-based C++ printer using SFINAE for compile-time static dispatch of variadic arguments.
This file contains hidden or 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
| // Copyright (c) December 2025 Félix-Olivier Dumas. All rights reserved. | |
| // Licensed under the terms described in the LICENSE file | |
| template<typename Variation> | |
| class IPrinter { | |
| public: | |
| template<typename... Args> | |
| auto print(Args&&... args) noexcept -> | |
| std::enable_if_t<std::is_void_v | |
| <decltype(std::declval<Variation>().print(std::declval<Args>()...))>, | |
| void> { static_cast<Variation*>(this)->print(std::forward<Args>(args)...); } | |
| }; | |
| class ConsolePrinter : public IPrinter<ConsolePrinter> { | |
| public: | |
| template<typename T> | |
| void print(const T& printable) const noexcept { | |
| std::cout << printable << std::endl; | |
| } | |
| }; | |
| int main() { | |
| IPrinter<ConsolePrinter> consolePrinter; | |
| consolePrinter.print("Hello World!"); | |
| consolePrinter.print(67); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment