3 ms·
I was a bit unclear there—I was referring to templates, not C++ macros. I believe that concepts in C++20 have improved the situation (although I haven't persona
by necubi 2y ago
I was a bit unclear there—I was referring to templates, not C++ macros. I believe that concepts in C++20 have improved the situation (although I haven't personally worked with a C++20 codebase and don't know how widely adopted it is in the ecosystem).
- pjmlp 2y agoStill there is no need for macros. The only thing you may complain about are error messages due to duck typing at compile time gone wrong, and even that is kind of already sorted out in C++17. Anyway, C++ today means C++23.
- pjmlp 2y agoC++17 example, showing polymorphism at compile time without macros. Naturally checking for speak() existence with enable_if, static_assert and type traits could be added, though this is an example, and nowdays we would make use of concepts anyway. #include <iostream> using namespace std; class Duck { public: void speak() const { cout << "quack"; } }; class Dog { public: void speak() const { cout << "auau"; } }; class Cat { public: void speak() const { cout << "miau"; } }; template<typename T> void speaking_animal(const T& animal) { animal.speak(); cout << "\n\n"; } template<typename... T> void speaking_farm(const T&... animals) { auto space_adder = [&](auto creature) -> void { creature.speak(); cout << " "; }; (space_adder(animals), ...); } int main() { Duck duck; Dog dog; Cat cat; speaking_animal(duck); speaking_animal(dog); speaking_animal(cat); speaking_farm(duck, dog, cat); } Available at https://godbolt.org/z/WWfx5jWfM https://godbolt.org/z/WWfx5jWfM