2013-05-04 104 views
0

我不知道为什么指针不能作为引用传递给函数。也许我错过了错误的重点。指针类型的类模板专门化中没有匹配函数

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*&' 

请帮帮忙,谢谢!

+0

看 - HTTP ://stackoverflow.com/questions/14492523/no-known-conversion-from-pointer-to-reference-to-pointer – Bill 2013-05-04 23:23:55

回答

1

因为引用不能绑定到右值,&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; 
    } 
+0

非常感谢。对我来说很奇怪,我必须看看那些右值。 – 2013-05-04 23:39:01

相关问题