我正在尝试用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关键字来声明一个模板函数。
发布于 2017-10-23 08:20:58
模板声明缺少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)发布于 2017-10-23 08:17:51
我知道我可以使用类标识符或类型名标识符
完全正确,但你也没有用。
template<T> <--- HERE it should be "class T" or "typename T"
T FindMaximum(T a, T b)https://stackoverflow.com/questions/46884722
复制相似问题