c++ - 如何定义函数模板中使用的函数?

标签 c++

我今天开始用C++学习模板,我试着写了一个简单的代码。然后我想使用模板参数(a)在原始函数(function)中编写另一个函数(display),但我找不到正确定义“display”函数的方法。有什么办法可以通过编译吗?还是应该使用class template(这个我还没有研究过,如果需要的话,我会马上看相关资料)?顺便说一句,我的母语不是英语,所以我用了一个小翻译器。我的某些描述可能看起来很奇怪,对此我深表歉意。

我了解到模板有其可变范围,所以我尝试添加{},但它不起作用。更重要的是,我不想将代码复制到“函数”中,所以我不知道该怎么做。

template <typename T>
void function(T a[],int n)
{
    cout<< "now you are in function." <<endl;
    for(int i = 0; i < n; i++)
    {
        display(a,i);//Here I have to use "a"
        cout << a[i] << " ";
    }
    cout << endl;
}

void display(T a[],int n)
{
    cout << "now you are in display." << endl;
    for(int i = 0; i < n; i++)
    {
        cout << a[n-i] << " ";
    }
    cout << endl;
}

这是编译器说的: 错误:变量或字段“显示”声明无效 void display(T a[],int n) 错误:“T”未在此范围内声明 但是我不能在“显示”功能之前使用其他类型名称。

最佳答案

您的代码有两个问题:

  1. display function 之后定义, 因此不能在 function 内使用;和
  2. display应该是一个模板函数,以便使用类型名称 T .

displayfunction 之后定义,编译器将无法找到 display当您尝试在 function 内调用它时.您可以声明 display在定义 function 之前,这基本上告诉编译器该函数在其他地方定义,或者您可以移动 display 的定义在`函数之上。

另外,你需要制作display还有一个模板,以便它可以使用类型 T .

您可以通过执行以下操作以最简单的方式解决这两个问题:

template <typename T>
void display(T a[],int n)
{
    // your code here
}

template<typename T>
void function(T a[],int n)
{
    // your code here
}

如果您真的想要 display 的定义在function之后, 你可以声明 display之前function定义:

template<typename T>
void display(T a[], int n);

template<typename T>
void function(T a[], int n)
{
    // your code here
}

template<typename T>
void display(T a[], int n)
{
    // your code here
}

编辑:更新后display要成为模板,您需要更新代码以相应地调用它:

template<typename T>
void function(T a[], int n)
{
    // ... beginning of the function ...
    for (int i = 0; i < n; i++)
    {
        display<T>(a, i); // Note the addition of the template parameter
        cout << a[i] << " ";
    }
    // ... rest of the function ...
}

关于c++ - 如何定义函数模板中使用的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57875004/

相关文章:

c++ - 将操作数据存储在 memcached 中是个好主意吗?

c++ - 在 MaxOSX10.12.4 上成功安装 OpenCV3 但它不起作用

C++:类型定义和嵌套类问题

c++ - 编译器错误 : invalid conversion from 'int' to 'int*' [-fpermissive]

c++ - 函数重载和方法重载的区别

c++ - 静态库中带有 std::cout 的 MSVC 2010 链接器错误 2005

c++ - SDL2 + Win32 API 菜单栏单击事件不起作用

c++ - 如何创建指针数组?

c++ - 2个线程如何共享同一个缓存行

c++ - 在类型实例化期间强制触发 static_assert