Advertisement
spikeysnack

longest template

Jul 4th, 2018
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. //degenerate case
  4. template<typename T>
  5. T& longest(T& a)  {return a;}
  6.  
  7. // regular case
  8. template<typename T>
  9.  T& longest( T& a, T& b)
  10.   {
  11.     std::string A(a);
  12.     std::string B(b);
  13.     return (A.length() >= B.length())? a: b;
  14.   }
  15.  
  16. // works for std:string, not for "string"
  17. template<typename T, typename... Args>
  18. T& longest( Args... args )
  19. {
  20.   return longest(  args...) ;
  21. }
  22.  
  23.  
  24.  
  25. int main ( int argc, char* argv[])
  26. {
  27.   std::string a , b, c, d;
  28.  
  29.   a = "a";
  30.   b = "ab";
  31.   c = "abc";
  32.   d = "abcd";
  33.  
  34.   std::string x = longest( a, b, c, d); // works fine
  35.  
  36. /* error
  37.     longest.cpp:66:19: note: in instantiation of function template specialization
  38.     'longest<char const[2], const char *, const char *, const char *>' requested here
  39. */
  40.   std::string y = longest( "1" , "22", "333", "4444"); // why are different types? Remedy?
  41.  
  42.   std::cout << x << std::endl;
  43.   std::cout << y << std::endl;
  44.  
  45.   return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement