tags:

views:

105

answers:

2

If I have one template class and template function like this

template <class T> T getMax (T a, T b) {
  return (a>b?a:b);
}

template <class T> class GetMax {
public:
    static T getMax(T a, T b) {
        return (a>b?a:b);   
    }       
};

Why are these not valid?

x=getMax(1, '2');               

but these are valid

x=getMax(1,2);

Does it mean that there is no type conversion in template function?

This is not valid

x=GetMax::getMax(1, 2);

Does it mean that for the template class, the type must be specified?

+3  A: 

What should getMax(1, '2'); return? An int, or a char? Think about it :)

You could write:

template <class T1, class T2> T1 getMax (T1 a, T2 b) {
  return (a>b?a:b);
}

But note that you are explicitly returning type 1, what might not work in a case like getMax('1',1000) because 100 would be converted to char type, and that wouldn't be large enough.

The latter is not valid because to use a class, you must first state what type it is -- this mechanism acts first, before type deduction.

It would work if you stated it :

class GetMax {
public:
    template <class T> 
    static T getMax(T a, T b) {
        return (a>b?a:b);   
    }       
};
Kornel Kisielewicz
I mean why '2' can not be converted to int implicitly?
skydoor
@skydoor, how should the compiler know if you want to return a `char` or a `int`?
Kornel Kisielewicz
@skydoor, the same question could be asked, why can't `1` be converted to char implicitly?
Kornel Kisielewicz
@skydoor: Because '2' is not an integer. It is a textual representation of one, yes, but so is "two", "TWO" or "II". Should all those be converted implicitly to the integer 2 as well? And if so, how about "deux", "to" or "zwei"? All of those are textual representations of the integer 2.
jalf
+3  A: 

1) There is type conversion, but it doesn't work together with type inference. Meaning when you specify the type (like getMax<int>(1,'2') or getMax<char>(1,'2')) it works, but if you don't, the compiler can't infer whether you want getMax<int> or getMax<char>.

2) Yes, template arguments are inferred only for function templates, not class templates.

sepp2k