开发者

Template Functions and Const/NonConst Reference Parameters

New to C++ and learning from books so I can be quite pedantic or miopic in my reasoning.

In the case of template functions, I have read that when a parameter is passed by Reference, only conversions from Reference / Pointer to NonConst to Reference / Pointer to Const are alllowed.

That means I believe that

template <typename T> int compare(T&, T&);  

should fail when calling compare(ci1, ci1), with ci1 开发者_如何学JAVAbeing consntant int, as conversions from Const to NonCost are not allowed for Reference parameters.

However it works in my compiler (Visual C++ 10). Can someone explain me what I get wrong?


template <typename T> int compare(T&, T&);  

template <typename T> int compare(T &v1,  T &v2)
{
    // as before
    cout << "compare(T, T)" << endl;
    if (v1 < v2) return -1;
    if (v2 < v1) return 1;
    return 0;
}


const int ci1 = 10;
const int ci2 = 20;

int i1 = 10;
int i2 = 20;

compare(ci1, ci1);     
compare(i1, i1);  


The call

compare( ci1, ci1 );

yields T as type const int (in your preferred notation).

The effective function signature is then

int compare( int const&, int const& )

You can use typeid(x).name() the check out what types you actually have.

Note: with g++ that yields some ungrokkable short forms, which you then need to use a special g++-specific runtime lib function to decode.

Cheers & hth.


T will be whatever type the variable is - in your case const int, so the final instantiation of compare will look like

// T = const int
int compare(const int& v1, const int& v2)

in your first case with compare(ci1,ci2) and like

// T = int
int compare(int& v1, int& v2)

with compare(i1,i2).


In the first case, the template is instantiated with T = const int, which is fine.

You will get an error if you try compare(i1, ci1), since that will fail to find a template argument compatible with both int & and const int &. Changing the signature to compare(const T &, const T &) will fix that problem.


In the case of compare(ci1, ci1); T will be const int. This is why it works


This is acceptable because the function can be instantiated when you substitute int const for T.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜