C++ C++;模板演绎-T成为指针类型
我有一个代码snippletC++ C++;模板演绎-T成为指针类型,c++,template-argument-deduction,C++,Template Argument Deduction,我有一个代码snipplet 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 =
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);
}
与
这就是结果
(我对第一名的期望)
模板
无效p(常数T*值)
{
std::cout从int*
到int*const&
的隐式转换序列比从int*
到const*
的隐式转换序列更好
后者包含a,而前者不包含
模板参数推断回答的是“我应该用T
替换什么类型”的问题,而不是“值的类型是什么”。对于Template void p(const T*value)
必须从参数的类型中去掉一个*
。谢谢你的回答。因此,编译器选择了引用重载,因为其中一个不包含常量转换,而另一个包含。我用指向模板void p(T*值)
的指针更改了重载,现在(没有常量转换)编译器选择了这一段。对于你答案的最后一段,我必须重新阅读并重新思考。
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
int* i = new int(5);
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;
}
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);
}