fork(3) download
  1. #include <iostream>
  2. #include <utility>
  3. using namespace std;
  4.  
  5.  
  6. template<typename T>
  7. struct factory_impl;
  8. // Left unspecified for now (which causes compliation failure if
  9. // not later specialized
  10.  
  11. template<typename T, typename... Args>
  12. T create(Args&&... args)
  13. {
  14. return factory_impl<T>::create(std::forward<Args>(args)...);
  15. }
  16.  
  17.  
  18. // Note, this can be specified in a header in another translation
  19. // unit. The only requirement is that the specialization
  20. // be defined prior to calling create with the correct value
  21. // of T
  22. template<>
  23. struct factory_impl<int>
  24. {
  25. // Call with 0 arguments or 1 argument
  26. static int create(int src = 0)
  27. {
  28. return src;
  29. }
  30. };
  31.  
  32. int main(int argc, char** argv)
  33. {
  34. int i = create<int>();
  35. int j = create<int>(5);
  36. // double d = create<double>(); // Fails to compile
  37.  
  38. std::cout << i << " " << j << std::endl;
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
0 5