指针类型的类模板专门化调用中没有匹配的函数

No matching function for call in class template specialization for a pointer type

本文关键字:函数 专门化 类型 指针 调用      更新时间:2023-10-16

我不知道为什么不能将指针作为引用传递给函数。也许我没有注意到错误的关键。

class Point{
public:
    Point(){}
};
template<typename KEY,typename VALUE>
class TemplTest{
public:
    TemplTest(){}
    bool Set(const KEY& key,const VALUE& value){
        return false;
    }
};
template<typename KEY,typename VALUE>
class TemplTest<KEY*,VALUE>{
public:
    TemplTest(){}
    bool Set(KEY*& key,const VALUE& value){
        return true;
    }
};
int main(){
    Point p1;
    TemplTest<Point*,double> ht;
    double n=3.14;
    ht.Set(&p1,n);
    return 0;
}
错误:

no matching function for call to 'TemplTest<Point*, double>::Set(Point*, double&)'
no known conversion for argument 1 from 'Point*' to 'Point*&'

请帮忙,谢谢!

因为引用不能绑定到右值,所以&p1是一个没有名称的右值,以绕过这个

Point *p1_ptr = &p1;
Point *&p1_ptr_ref = p1_ptr;
ht.Set( p1_ptr_ref, n);

或者您可以将const添加到键

    bool Set( KEY* const& key,const VALUE& value){
//                 ^^^^^
        return false;
    }