没有类关键字的模板函数

Delcaring template function without class keyword

本文关键字:函数 关键字      更新时间:2023-10-16

我正在尝试在 C++-11 中进行模板编程。

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

这两个函数

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

给出错误

‘T’ has not been declared template<T>

但是从评论(我从教程中复制的)中,我知道我可以使用class identifiertypename identifier.

我的代码有什么问题。我做了一个没有 class 关键字的模板函数。

模板声明缺少 classtypename 关键字。

取代:

template<T>
T FindMaximum(T a, T b)

跟:

template<typename T>
T FindMaximum(T a, T b)
-- OR --  
template<class T>
T FindMaximum(T a, T b)

了解我可以使用类标识符或类型名标识符

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

template<T> <--- HERE it should be "class T" or "typename T"
T FindMaximum(T a, T b)