2 ms·
Still 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 kin
by pjmlp 2y ago
Still 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