源代码在c ++中调用错误的模板类函数,如何修复
Source code is calling wrong template class function in c++, how to fix?
我在这里遇到了一个小问题,我不确定如何修改我的代码来解决这个问题。这也是来自 c++ primer plus 的问题。
法典:
#include <iostream>
#include <cstring>
template <typename T>
//#1
T maxn(T array[], int n); // function call always go to this one
//#2
template <class T> T maxn(char* ptr, int n); // problem is this, I want it to -
// work with array of pointers to strings (char* names[])
int main(){
char* names[] = {"Bobby", "Jack"};
int array[] = {5,9,2,11,15};
maxn(array, 5); // call works and goes to #1
maxn(names, 2); // not going to #2 since it also matches #1 signature...
}
好吧,我知道我的问题是什么,那就是我对指针数组的调用也满足 #1 的参数条件,但我希望它转到 #2..无论如何我可以让这种情况发生吗?根据我的练习,我必须有一个模板类的规范,所以我不能只是摆脱它。希望你能理解。
我的全部源代码在这里:
#include <iostream>
#include <cstring>
template <typename T>
T maxn(T array[], int n);
template <class T> T maxn(char* ptr[], int n);
int main()
{
char* names[] = {
"Zara Ali",
"Hinaa Ali",
"Nuha Ali",
"Sara Ali",
};
int array[] = {5,9,2,11,15};
char* pointer = maxn(names, 4.0);
return 0;
}
template <typename T>
T maxn(T array[], int n)
{
T temp;
temp = array[0];
for(int i = 0; i < n-1; i++)
{
for(int j = i+1; j < n; j++)
{
if(temp < array[j])
{
temp = array[j];
//std::cout << temp;
}
}
}
std::cout << "hello";
return temp;
//std::cout << "Max: " << temp << std::endl;
}
template <class T> T maxn(char* ptr[], int n)
{
std::cout << ptr;
char* pointer;
char tmp = strlen(ptr[0]);
for(int i = 1; i < n-1; i++)
{
for(int j = i+1; j < n; j++)
{
if(tmp < strlen(ptr[j]))
{
tmp = strlen(ptr[j]);
char* pointer = &(ptr[j]);
}
}
}
return*pointer;
}
names
的类型是 char const*[2]
; 转换为指针后,它变得char const**
,而不是char*
。 不能调用非模板函数,因为没有从char const**
到char*
的转换。
此外,当然,特殊版本不应该是模板,因为它仅适用于类型 char const**
:
char const*
maxn( char const** ptr, int n )
{
// ...
}
大概是你想要的。 (否则,您必须指定T
明确地,即:maxn<T>( names, 22 );
. 无论您想T
什么是。 但由于在模板版本中,T
必须是指向的类型,我宁愿怀疑这不是你想要的。
向模板添加另一个参数以仅接受数组引用,而不接受降级为指针的数组参数。
template <class T, int N> T maxn(T (&array)[N], int n);
指向
char
的指针数组的类型特定重载应声明为:
template <size_t N> const char * maxn(const char* (&ptrs)[N], int n = N);
当前声明在第一个参数中采用指向char
的指针,而不是指向char
的指针数组。
相关文章:
- 如何通过派生类函数更改基类中的向量
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 库函数需要一个 std::function<void(void)>,如何传入类函数?
- 在类函数中初始化外部作用域变量
- c++ 在非类函数中使用类变量
- SDL_PollEvent() 无法捕获类函数内部SDL_QUIT?
- 从类成员函数到类 C 函数指针的转换
- 如何在模板类函数中分配结构值?
- 有没有办法将重载的类函数绑定到函数对象?
- 启动类函数作为失去引用的线程
- C++调用使用重写函数的父类函数
- 将值传递到另一个类函数在打印时为零
- 计算对类函数的所有调用次数
- 由于签名差异,调用了错误的子类函数
- 使用宏调用类函数
- 虚拟基类函数中派生类的大小
- 模板类/函数中的交叉前向声明
- 如何修复类函数"prototype does not match"和"cadidate is"错误
- 源代码在c ++中调用错误的模板类函数,如何修复
- 类函数原型与定义不匹配-如何修复