Advertisement
mbazs

PTS vs if constexpr

Dec 19th, 2021
1,336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.65 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. // partial template specialization
  4. template <class T>
  5. struct A {
  6.     void whoami() { std::cout << "A" << std::endl; }
  7. };
  8. template <class T>
  9. struct A<T*> {
  10.     void whoami() { std::cout << "A*" << std::endl; }
  11. };
  12.  
  13. // constexpr if
  14. template <class T>
  15. struct B {
  16.     void whoami() {
  17.         if constexpr (!std::is_pointer<T>()) {
  18.             std::cout << "B" << std::endl;
  19.         } else {
  20.             std::cout << "B*" << std::endl;
  21.         }
  22.     }
  23. };
  24.  
  25. int main()
  26. {
  27.     A<int> a0;
  28.     a0.whoami();
  29.     A<int*> a1;
  30.     a1.whoami();
  31.  
  32.     B<int> b0;
  33.     b0.whoami();
  34.     B<int*> b1;
  35.     b1.whoami();
  36.  
  37.     return 0;
  38. }
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement