源代码在c ++中调用错误的模板类函数,如何修复

Source code is calling wrong template class function in c++, how to fix?

本文关键字:类函数 何修复 错误 调用 源代码      更新时间:2023-10-16

我在这里遇到了一个小问题,我不确定如何修改我的代码来解决这个问题。这也是来自 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的指针数组。