metaprogramming/conditional/cond-5.cc - Selection one of two functions at compile time. | Lecture 6 - slide 35 : 40 Program 1 |
// An illustration of function objects. Very close to the program on page 787 of "The C++ Programming Language" 4ed. #include <iostream> #include <type_traits> // Conditional is a syntactial embellishment of the application of underlying conditional template: template<bool B, typename T, typename F> using Conditional = typename std::conditional<B, T, F>::type; struct X{ void operator()(int x){ std::cout << "X: " << x << std::endl; } // ... }; struct Y{ void operator()(int y){ std::cout << "Y: " << y << std::endl; } // ... }; void f(){ Conditional<(sizeof(int)>4), X, Y>{}(7); // Select either X or Y depending on the value of sizeof(int)>4. // Y is selected, instantiated, and called on 7. Y{}(7); // Equivalent. Y: 7 using Z = Conditional<std::is_polymorphic<X>::value, X, Y>; // X is not polymorphic, therefore Z becomes an alias of Y. Z zz{}; // makes an X or a Y zz(8); // calls an X og a Y. // Y: 8 } int main(){ std::cout << "size(int): " << sizeof(int) << std::endl; // 4 on my laptop. f(); }