C++ 重载模板和参数匹配-C++;底漆?
我只是想确认这是否是一个输入错误,或者我不明白函数模板参数匹配是如何工作的。给定这两个函数定义:C++ 重载模板和参数匹配-C++;底漆?,c++,templates,C++,Templates,我只是想确认这是否是一个输入错误,或者我不明白函数模板参数匹配是如何工作的。给定这两个函数定义: // print any type we don't otherwise handle template <typename T> string debug_rep(const T &t) { ostringstream ret; // see 8.3 ret << t; // uses T's output operator to print a repre
// print any type we don't otherwise handle
template <typename T> string debug_rep(const T &t)
{
ostringstream ret; // see 8.3
ret << t; // uses T's output operator to print a representation of t
return ret.str(); // return a copy of the string to which ret is bound
}
// print pointers as their pointer value,
// followed by the object to which the pointer points
// NB: this function will not work properly with char*; see 16.3
template <typename T> string debug_rep(T *p)
{
ostringstream ret;
ret << "pointer: " << p; // print the pointer's own value
if (p)
ret << " " << debug_rep(*p); // print the value to which p points
else
ret << " null pointer"; // or indicate that the p is null
return ret.str(); // return a copy of the string to which ret is bound
}
//打印我们无法处理的任何类型
模板字符串调试代表(常量T&T)
{
ostringstream ret;//参见8.3
retT
是const-string*
,因此const-T&
是const-string*const&
(这就是为什么有些人更喜欢“右边的const”排序:T-const&
,string-const*
,等等。然后它就组合得很整齐。)哦!我现在看到了。因为函数参数中的const
是顶级const
,所以被传递(并被保留)的那个“低级别<代码> const 。当通过指针或引用类型时,保留了低级<代码> const 。现在,您更清楚地提到了<代码> const <代码>的位置,在我的头上点击了一下:)(主题外,但我只见过C++中使用的这些术语……)我是stackoverflow的新手,我不知道如何接受你的答案。我想这是因为它在评论中。等等,那么书中有一个打字错误?debug\u rep(const string*&)
应该是debug\u rep(const string*const&)
-根据你的评论,这更有意义。
const string *sp = &s;
cout << debug_rep(sp) << endl;