fork download
  1. #include <iostream>
  2.  
  3. // in the normal case, just the identity
  4. template<class T>
  5. struct item_return{ typedef T type; };
  6.  
  7. template<class T>
  8. typename item_return<T>::type foo(){ return T(); }
  9.  
  10. template<>
  11. struct item_return<float>{ typedef int type; };
  12.  
  13. template<>
  14. int foo<float>(){ return 42; }
  15.  
  16. // might want to stick to the following
  17. // so you only need to update the return-type in one place
  18. // namely, the `item_return` specialization
  19. //template<>
  20. //item_return<float>::type foo<float>(){ ... }
  21. // note: No `typename` needed, because `float` is not a dependent type
  22.  
  23. int main(){
  24. std::cout << "out = " << foo();
  25. }
Compilation error #stdin compilation error #stdout 0s 16064KB
stdin
Standard input is empty
compilation info
prog.cpp: In function ‘int main()’:
prog.cpp:24:31: error: no matching function for call to ‘foo()’
  std::cout << "out = " << foo();
                               ^
prog.cpp:8:31: note: candidate: template<class T> typename item_return<T>::type foo()
 typename item_return<T>::type foo(){ return T(); }
                               ^~~
prog.cpp:8:31: note:   template argument deduction/substitution failed:
prog.cpp:24:31: note:   couldn't deduce template parameter ‘T’
  std::cout << "out = " << foo();
                               ^
stdout
Standard output is empty