【问题标题】:How can I define the function used in a function template?如何定义函数模板中使用的函数?
【发布时间】:2019-09-10 16:35:44
【问题描述】:

我今天开始学习 C++ 中的模板,并尝试编写一个简单的代码。然后我想使用模板参数(a)在原始函数(函数)中编写另一个函数(显示),但我找不到正确定义“显示”函数的方法。有没有办法通过编译?或者我应该使用类模板(我还没有研究过,但如果需要,我会立即阅读相关资料)?顺便说一句,我的母语不是英语,所以我用了一个小翻译。我的某些描述可能看起来很奇怪,对此我很抱歉。

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

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;
}

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

【问题讨论】:

  • 为什么你在display 之前没有template &lt;typename T&gt;,就像你对function 所做的那样?
  • 不能在函数内直接创建函数。但不使用模板时也是如此。
  • 你记得在调用之前声明display函数吗?
  • 哦,当你开始学习更多关于 C++ 和模板的知识时,如果你真的想传递数组而不仅仅是指针,那么像 template&lt;typename T, size_t N&gt; void function(T (&amp;a)[N]) { ... } 这样的模板可能会更好。或者更好的是,不要使用 C 风格的数组和指针,使用 std::arraystd::vector

标签: c++


【解决方案1】:

你的代码有两个问题:

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

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

此外,您还需要将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 之后,您可以在定义 function 之前声明 display

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 ...
}

【讨论】:

  • 所以每当我需要使用“T”类型时,我都应该使用“template”,对吗?
  • @CursorCC 是的。您可以将其命名为任何名称(不仅仅是T)并获得相同的效果,但这取决于您。
猜你喜欢
  • 1970-01-01
  • 2011-02-24
  • 2014-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多