2
#include <iostream>
using namespace std;

template <class MyType>
MyType GetMax (MyType a, MyType b, MyType c) {
  return std::max(std::max(a, b), c);
}

int main () {
  int a = 5, b = 6, c = 7, d;
  char e [] = "1", f [] = "2", g [] = "3", h; 
  d=GetMax<int>(a,b,c);
  cout << d << endl;
}

error: no matching function for call to 'GetMax(char [2], char [2], char [2])'

The program works fine with int but i am not sure what the problem is for char

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
user1082764
  • 1,973
  • 9
  • 26
  • 40
  • 2
    remove `` in `GetMax(a,b,c)` and let it deduce types for u. also if u use it with `char*`s it will compare pointers not content. if u want to compare content of strings use `std::string` (or modify ur func to take a comparator) – Kal Sep 26 '13 at 21:12
  • Related (because `std::max` isn't liking my `char` vs. `int` comparison): https://stackoverflow.com/questions/2304732/how-do-i-specify-an-integer-literal-of-type-unsigned-char-in-c – Andrew Oct 11 '20 at 04:56

2 Answers2

2

You are declaring C-style strings, nor chars.

If you want to use GetMax with chars your code should be something like this:

 char e = '1', f = '2', g = '3', h; 
 h = GetMax<char>(e, f, g);

Note that in this particular case the compiler can determine the signature for GetMax, so you can reduce the call to just:

 h = GetMax(e, f, g);
Paul R
  • 208,748
  • 37
  • 389
  • 560
0

It doesn't have a problem with char, it has a problem with char *, also known as "c-style strings".

There is no operator< for c-style strings (char *), so std::max doesn't work. You'll have to implement it yourself with strcmp OR use std::string instead.

rabensky
  • 2,864
  • 13
  • 18
  • actually yes there is `operator<` for pointers, i thikn the problem is he explicitly specified the template arg instead of letting it deduce it or giving the right type – Kal Sep 26 '13 at 21:12
  • @kal fine, there is. But not the one he wanted... :p – rabensky Sep 26 '13 at 21:13