C ++操作符查找误解 [英] C++ operator lookup misunderstanding

查看:198
本文介绍了C ++操作符查找误解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下一个案例中遇到麻烦:

I have a trouble with next case:

template<typename T>
void test(const T &ref){
     cout << "By reference";
}

template<typename T>
void test(const T *ptr){
     cout << "By pointer";
}

我发送给 方法将总是通过引用传递到重载。即使这样:

Any parameter that I sent to the test() method will always pass to overloading with reference. Even this:

int *p = 0; test(p);

有人能告诉我为什么参考具有这么高的优先级,

Can someone tell me why reference has so high priority and the place in standart where to read about this.

哦...我不留心!我必须为指针case指定const和非const重载:

Oh... I was inattentive! I have to specify both const and non-const overloading for a pointer case:

template<typename T>
void test(const T &ref){
     cout << "By reference";
}

template<typename T>
void test(T *ptr){
     cout << "By pointer";
}

template<typename T>
void test(const T *ptr){
     cout << "By const pointer";
}


推荐答案

> const T * 表示 T const ,但不是 T *

Because const T * means that T is const but not T *.

#include <iostream>
template<typename T>
void test(const T &ref){
     std::cout << "By reference\n";
}

template<typename T>
void test( T * const ptr){
     std::cout << "By pointer\n";
}


int main()
{
    int *p;
    test(p);
    return 0;
}



您也可以使用 typedef T * PtrT ,然后将 T * const 更改为 const PtrT

template <typename T>
using PtrT = T *;

template<typename T>
void test(const PtrT<T> ptr){
     std::cout << "By pointer\n";
}

这篇关于C ++操作符查找误解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆