开发者

C++ template class and template function

开发者_运维技巧

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?


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);   
    }       
};


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜