c++ - 源代码在 C++ 中调用了错误的模板类函数,如何解决?

标签 c++

我在这里遇到了一个小问题,我不确定如何修改我的代码来解决这个问题。这也是来自 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必须是指向类型, 我宁愿怀疑这不是你想要的。)

关于c++ - 源代码在 C++ 中调用了错误的模板类函数,如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27711462/

相关文章:

c++ - 如何在 C++ 中将值与模板和 boost 进行比较?

c++ - 在 C++ 中 << 和 >> 之间的运行时切换

c++ - opencv中灰度图像的熵

c++ - 调用宏时参数太多

c++ - _T ("x") 没有按预期行事

c++ - 如果线程本身退出,则从从线程调用的方法强制返回

python - Python 3.6 的 boost 和 dlib 安装期间出错

c++ - 在 linux 中监控挂载文件夹

c++ - 从基类引用调用派生类方法

c++ - 互斥体上的条件断点未触发