【发布时间】:2021-11-18 03:23:27
【问题描述】:
考虑下面的代码:
#include <iostream>
// General overload using a template
template <typename SomeType>
void some_func(const SomeType p) {
std::cout << "Using the general function" << std::endl;
}
// Specific overload, accepting a 'const double*' type
void some_func(const double* p) {
std::cout << "Using the function accepting a const double*" << std::endl;
}
int main() {
// This one uses the specific overload, as expected
const double *a = new double(1.1);
some_func(a);
delete a;
// This one uses the general function rather than the second overload
double *b = new double(1.1);
some_func(b);
delete b;
return 0;
}
在这段代码中,some_func 函数有两个重载。第一个是最常见的重载,使用模板来捕获几乎任何类型。第二个重载是一个特定的重载,接受 const double* 类型作为其参数。
在main 函数中,我首先创建const double* 类型的变量a。将a 提供给some_func 时,将选择第二个过载。这正如预期的那样。其次,我创建了一个double* 类型的变量b(所以没有const)。当将变量b 提供给some_func 时,它会选择第一个重载。我预计它会选择第二个重载,因为(我认为)它应该能够将类型double* 隐式转换为const double*。为什么在这种情况下它选择第一个重载而不是第二个重载?
为了完整起见,这是程序的输出:
$ g++ main.cpp
$ ./a.out
Using the function accepting a const double*
Using the general function
【问题讨论】:
-
提示:您希望
p在每个函数中具有什么值? -
参数应完全匹配,以便编译器选择非模板函数。所以选择不是“错误的”。
-
如果您将函数编写为
void some_func(double const * p)与您所拥有的相同,为什么首选模板是否有意义? -
@chux-ReinstateMonica 在将
b传递给some_func时,我希望p在两个重载中都具有const double *类型。然而,事实证明p在模板化重载中属于double* const类型,在特定重载中属于const double*类型。考虑到这一点,我理解它为什么使用模板化重载。
标签: c++ implicit-conversion overload-resolution