首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不带类关键字的删除模板函数

不带类关键字的删除模板函数
EN

Stack Overflow用户
提问于 2017-10-23 08:16:04
回答 2查看 1.7K关注 0票数 1

我正在尝试用C++-11进行模板编程.

代码语言:javascript
复制
#include <iostream>

using namespace std;

/*
 * Function templates are special functions that can operate with generic types. This allows us to create a function template whose
 * functionality can be adapted to more than one type or class without repeating the entire code for each type.
 * In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to
 * pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow
 * to pass also types to a function. These function templates can use these parameters as if they were any other regular type.
 */

/* The format for declaring function templates with type parameters is:
 *   template <class identifier> function_declaration;
 *   template <typename identifier> function_declaration;
*/

template <class T>
T GetMax (T a, T b) {
    T result;
    result = (a>b)? a : b;
    return (result);
}

template<T>
T FindMaximum(T a, T b)
{
    T result;
    result = (a > b) ? a : b;
    return result;
}

int main () {
    int i=5, j=6;
    int k, c;
    long l=10, m=5;
    long n, d;


    k=GetMax<int>(i,j);
    n=GetMax<long>(l,m);

    cout << k << endl;
    cout << n << endl;

    c=FindMaximum<int>(j, i);
    d=FindMaximum<long>(l,m);

    cout << c << endl;
    cout << d << endl;

    return 0;
}

这两种功能

代码语言:javascript
复制
    c=FindMaximum<int>(j, i);
    d=FindMaximum<long>(l,m);

给出错误

代码语言:javascript
复制
‘T’ has not been declared template<T>

但是,从评论(我从教程中复制的)中,我了解到我可以使用class identifiertypename identifier

我的密码怎么了。我不使用class关键字来声明一个模板函数。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-10-23 08:20:58

模板声明缺少classtypename关键字。

取代:

代码语言:javascript
复制
template<T>
T FindMaximum(T a, T b)

通过以下方式:

代码语言:javascript
复制
template<typename T>
T FindMaximum(T a, T b)
-- OR --  
template<class T>
T FindMaximum(T a, T b)
票数 3
EN

Stack Overflow用户

发布于 2017-10-23 08:17:51

我知道我可以使用类标识符或类型名标识符

完全正确,但你也没有用。

代码语言:javascript
复制
template<T> <--- HERE it should be "class T" or "typename T"
T FindMaximum(T a, T b)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46884722

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档