fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // Test struct.
  5. template<class T>
  6. struct Foo
  7. {
  8. T foo;
  9. };
  10.  
  11. // Struct specialization
  12. template<>
  13. struct Foo<bool>
  14. {
  15. static const int val = 46;
  16. };
  17.  
  18. // #1 Ordinary template
  19. template<class T>
  20. struct functionWrapper {
  21. static T foo() {
  22. return T();
  23. }
  24. };
  25.  
  26.  
  27. // #2 Template specialization
  28. template<>
  29. struct functionWrapper<int> {
  30. static int foo() {
  31. return 42;
  32. }
  33. };
  34.  
  35.  
  36. // #3 Template specialization with template as parameter
  37. template<class T>
  38. struct functionWrapper<struct Foo<T>> {
  39. static Foo<T>* foo() {
  40. return new Foo<T>();
  41. }
  42. };
  43.  
  44.  
  45.  
  46.  
  47.  
  48. int main() {
  49. cout << functionWrapper<bool>::foo() << endl;
  50. cout << functionWrapper<int>::foo() << endl;
  51.  
  52. Foo<bool> *obj = functionWrapper<Foo<bool>>::foo();
  53. cout << obj->val;
  54. delete obj;
  55.  
  56. return 0;
  57. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
0
42
46