我有此代码段
template <typename T>
void p(const T* value)
{
std::cout << *value << std::endl;
}
template <typename T>
void p(const T& value)
{
std::cout << value << std::endl;
}
int main()
{
int* i = new int(5);
p(i);
}
1)根据https://cppinsights.io/,模板功能等效于
template <typename T>
void p(const T* value)
{
std::cout << *value << std::endl;
}
template <typename T>
void p(const T& value)
{
std::cout << value << std::endl;
}
/* First instantiated from: insights.cpp:18 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
void p<int *>(int *const & value)
{
std::cout.operator<<(value).operator<<(std::endl);
}
#endif
对我来说,这很奇怪。根据“有效的现代c ++的第1项”,唯一可以将T推导出为T&(或我猜想的T *)的情况是函数参数是通用引用(转发引用)时。但是,将这种情况T推导出为int *,但是如果只是一个指针,则返回参数。
2)如果我替换
int* i = new int(5);
with
const int* i = new int(5);
这是结果(我对第一名的期望)
template <typename T>
void p(const T* value)
{
std::cout << *value << std::endl;
}
/* First instantiated from: insights.cpp:18 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
void p<int>(const int * value)
{
std::cout.operator<<(*value).operator<<(std::endl);
}
#endif
template <typename T>
void p(const T& value)
{
std::cout << value << std::endl;
}
3)返回1),如果我消除了过载
template <typename T>
void p(const T& value)
所以我只有
template <typename T>
void p(const T* value)
{
std::cout << *value << std::endl;
}
int main()
{
int* i = new int(5);
p(i);
}
结果是
template <typename T>
void p(const T* value)
{
std::cout << *value << std::endl;
}
/* First instantiated from: insights.cpp:12 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
void p<int>(const int * value)
{
std::cout.operator<<(*value).operator<<(std::endl);
}
#endif
int main()
{
int * i = new int{5};
p(i);
}
您能否解释一下为什么T可以推导为问题1)int *问题2)int *的原因?我也不了解模板参数推导3)的顺序。
感谢任何提示/解释。
从int *
到int * const &
的隐式转换顺序比从int *
到const int *
的隐式转换顺序好。
后者包含qualification conversion,而前者不包含。