【问题标题】:C++ operator lookup misunderstandingC++ 运算符查找误区
【发布时间】:2015-12-18 14:11:59
【问题描述】:

我对下一个案例有疑问:

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

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

我发送给test() 方法的任何参数都将始终通过引用传递给重载。即使这样:

int *p = 0; test(p);

谁能告诉我为什么参考文献具有如此高的优先级以及在标准中的位置阅读此内容。

哦...我不专心!我必须为指针情况指定 const 和非 const 重载:

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

【问题讨论】:

  • 旁注:删除模板并将T 替换为int 后,g++ 4.8.4 选择了指针重载

标签: c++ pointers reference overloading operator-precedence


【解决方案1】:

因为const T * 表示Tconst 而不是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";
}

【讨论】:

    【解决方案2】:

    你能检查一下模板中使用的是哪种类型,是 int 还是 int*?我怀疑您将 T 检查为 int,但编译器将 T 解释为 int* 并使用参考模板。

    尝试使用

    test<int>(p);
    

    明确指定类型

    【讨论】:

    • 您没有回答“有人能告诉我为什么参考文献具有如此高的优先级以及在标准中的位置可以阅读有关此内容。”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    相关资源
    最近更新 更多