没有类关键字的模板函数
Delcaring template function without class keyword
我正在尝试在 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
关键字的模板函数。
模板声明缺少 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)
我了解我可以使用类标识符或类型名标识符
完全正确,但你也没有使用。
template<T> <--- HERE it should be "class T" or "typename T"
T FindMaximum(T a, T b)
相关文章:
- 如何确保C++函数在定义之前声明(如override关键字)
- C++函数的关键字?
- 应用于运算符而不是构造函数的显式关键字
- 如何通过 boost::p ython 重命名构造函数的关键字参数
- 是否建议在函数中使用using关键字
- C++ 如何将关键字"friend"与两个类的成员函数一起使用 相互包含
- 为什么 c++ 使用 throw() 关键字来指示函数不会引发任何异常
- 统一内存分配库的函数关键字
- 如何使用 "using" 关键字定义函数原型/签名
- 在 new 关键字中,由默认构造函数初始化的类中的元素是否也使用 new 关键字在C++?
- C++带有 using 关键字和参数包的模板函数
- 如何在 C++ 的 lambda 函数中传递同名的局部变量和参数(使用此关键字)?
- g++ 6.3,avx 内联函数上的 Kahan 求和用易失性关键字进行序列化
- ELI5 函数名称后面的"&&"关键字是什么意思
- 为什么静态成员函数定义不能有关键字"static"?
- 带有 "this" 关键字的 Java Copy 构造函数
- C++不使用"inline"或"static"无类函数的关键字时出现重定义链接错误
- 为什么带有 const 关键字的构造函数可以工作,而没有它就不能工作?
- 将 final 关键字添加到没有基类(未派生)的类中的虚函数是否有意义
- 虚函数关键字