我正在尝试用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 identifier
或typename identifier
。
我的代码出了什么问题。我在没有class
关键字的情况下声明了一个模板函数。
答案 0 :(得分:3)
您的模板声明缺少class
或typename
关键字。
替换:
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)
答案 1 :(得分:2)
我知道我可以使用类标识符或类型名称标识符
完全正确,但你没有使用过。
template<T> <--- HERE it should be "class T" or "typename T"
T FindMaximum(T a, T b)