fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. void foo(int i) { std::cout << "foo " << i << std::endl; }
  5. void bar(int i) { std::cout << "bar " << i << std::endl; }
  6. void foobar(int f) { std::cout << "foobar " << f << std::endl; }
  7.  
  8. template <typename T> struct DefaultF;
  9.  
  10. template <>
  11. struct DefaultF<int>
  12. {
  13. static constexpr void (*F)(int) = &foo;
  14. };
  15.  
  16. template <>
  17. struct DefaultF<float>
  18. {
  19. static constexpr void (*F)(int) = &foobar;
  20. };
  21.  
  22. template<class T, void (*F)(int) = DefaultF<T>::F>
  23. void MyF(const std::string&, const T& t) {
  24. F(t);
  25. }
  26.  
  27. int main() {
  28. MyF<int>("test", 42);
  29. MyF<int, &bar>("test", 42);
  30. MyF<float>("test", 42.f);
  31. // MyF<char>("test", '*'); // Won't compile, no DefaultF<char>::F
  32. }
  33.  
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
foo 42
bar 42
foobar 42