Advertisement
Guest User

Untitled

a guest
Jul 9th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <type_traits>
  4.  
  5. using namespace std;
  6.  
  7. class Policy1 {
  8. };
  9.  
  10. class Policy2 {
  11. };
  12.  
  13. /********** General settings *********/
  14. template<typename Policy>
  15. struct PolicyTraits {
  16.   static const bool somePolicyProperty = false;
  17.  
  18.   static const bool anotherPolicyProperty = true;
  19. };
  20.  
  21. /****** Overriding settings for Policy1       ****************/
  22. template<>
  23. struct PolicyTraits<Policy1> {
  24.   static const bool somePolicyProperty = false;
  25.  
  26.   static const bool anotherPolicyProperty = false;
  27. };
  28.  
  29. class SomeClass {
  30. public:
  31.  
  32.   // Some general template
  33.   template<typename Policy, typename ValueType>
  34.   void SomeFunction(Policy policy, ValueType value) {
  35.     cout << "General template: " << value << endl;
  36.   }
  37.  
  38.   // The specialization is not avaliable for Policy1
  39.   template<typename Policy>
  40.   void SomeFunction(Policy policy, int value, typename enable_if<PolicyTraits<Policy>::anotherPolicyProperty>::type* = 0) {
  41.     cout << "Some function: integer " << value << endl;
  42.   }
  43. };
  44.  
  45. int main() {
  46.   cout << boolalpha;
  47.   cout << PolicyTraits<Policy1>::anotherPolicyProperty << endl;  // false
  48.   cout << PolicyTraits<Policy2>::anotherPolicyProperty << endl;  // true
  49.  
  50.   SomeClass someClass;
  51.  
  52.   someClass.SomeFunction(Policy2(), "policy 2");  // correct: General template
  53.   someClass.SomeFunction(Policy2(), 123);  // correct: Specialization
  54.  
  55.   someClass.SomeFunction(Policy1(), "policy 1");  // correct: General template
  56.   someClass.SomeFunction(Policy1(), 456);  // correct: General template
  57.   return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement