code_junkie

Template Constraints C++

Nov 11th, 2011
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. interface IFoo
  2. {
  3. }
  4.  
  5.  
  6. class Foo<T> where T : IFoo
  7. {
  8. }
  9.  
  10. class Bar : IFoo
  11. {
  12. }
  13.  
  14. class Simpson
  15. {
  16. }
  17.  
  18. class Program
  19. {
  20. static void Main(string[] args)
  21. {
  22. Foo<Bar> a = new Foo<Bar>();
  23. Foo<Simpson> b = new Foo<Simpson>(); // error CS0309
  24. }
  25. }
  26.  
  27. class IFoo
  28. {
  29. public:
  30. typedef int IsDerivedFromIFoo;
  31. };
  32.  
  33. template <typename T>
  34. class Foo<T>
  35. {
  36. typedef typename T::IsDerivedFromIFoo IFooGuard;
  37. }
  38.  
  39. template <class T>
  40. int compute_length(T *value)
  41. {
  42. return value->length();
  43. }
  44.  
  45. string s = "test";
  46. vector<int> vec;
  47. int i = 0;
  48.  
  49. compute_length(&s);
  50. compute_length(&vec);
  51.  
  52. compute_length(&i);
  53.  
  54. template<class t> class FOO { private: FOO(){}};
  55.  
  56. template<> class FOO<int>{public: FOO(){}};
  57.  
  58. template<> class FOO<float>{public: FOO(){}};
Add Comment
Please, Sign In to add comment