【发布时间】:2020-01-21 16:16:48
【问题描述】:
考虑以下 sn-p:
template <class T>
struct remove_pointer
{
};
template <class T>
struct remove_pointer<T*>
{
typedef T type;
};
template <typename T>
T
clone(const T& v)
{
return v;
}
template <typename T, typename U = typename remove_pointer<T>::type>
T
clone(const U& v)
{
return new U(v);
}
int main()
{
auto foo = clone<double>(42.0);
return 0;
}
此代码会产生编译错误:
In function 'int main()':
30:34: error: call of overloaded 'clone(double)' is ambiguous
30:34: note: candidates are:
14:1: note: T clone(const T&) [with T = double]
22:1: note: T clone(const U&) [with T = double; U = double]
为什么编译器在第 22 行派生 T=double, U=double?我认为只有当T 是指针类型时它才应该通过。
【问题讨论】:
-
默认模板仅在未提供或推导时使用。在这里推导出来。
-
明白!如果 T 是指针,我可以让专门的重载通过吗?
-
您希望能够拥有
clone<double*>(42.0)。但是double* p = /*..*/; clone<double*>(p)呢? -
你想达到什么目的?如果
clone得到一个T*它应该返回一个T? -
当给定
int**时,clone应该做什么?
标签: c++ c++11 templates default-template-argument