|
| |||||||||
| Tags: function template, syntax, template, templates |
![]() |
| | Thread Tools | Search this Thread |
|
#1
| |||
| |||
| Syntax/Semantics for a C++ "Function Template"?
I am learning a C++. This is my first programming langage that I am learning. I have covered up major basic portion of C++. Now I am stucked on syntax/semantics for function templates. Firstly I am finding it difficult to understand function templates and in that I am not able to get the exact way to code function templates in C++. |
|
#2
| ||||
| ||||
| Re: Syntax/Semantics for a C++ "Function Template"?
We will take a very simple function to swap two integer type numbers to explain the syntax for function templates in C++. Code: void Swp(int& n1, int& n2)
{
int n3 = n1;
n1 = n2;
n2 = n3;
} But now consider if we had to swap the float type, char type and string type data. Although similar type of action is performed but with different data-types. It would really be time consuming to code such querry that too which is performing same action. Thus can the need for function templates. Now the above code using function template would be: Code: template<typename N>
void Swp(N& n1, N& n2)
{
N n3 = n1;
n1 = n2;
n2 = n3;
}
void main()
{
int a,b;
float p,q;
char w,x;
...
Swp(a,b);
Swp(p,q);
Swp(w,x);
.
.
.
} Last edited by kelfro : 11-11-2009 at 06:25 PM. |
|
#3
| ||||
| ||||
| Re: Syntax/Semantics for a C++ "Function Template"?
I had also studied C, C++. I found this topic very hard to study. Many times I was confused with its sytax and symentics. The basic syntax for declaring the C++ function templates using type arguments is as follows: Using keyword typename, template <typename identifier> function_declaration; You can also make use keyword class in place of typename, template <class identifier> function_declaration; |
|
#4
| ||||
| ||||
| Re: Syntax/Semantics for a C++ "Function Template"?
The definition for template should always begin with a keyword 'template'. The parameters of the templates for the function are then written besides the keyword 'template' that are enclosed in '<' '>' brackets. Syntax for function template: template< typename T > or template< class ElementType > or template< typename BorderType, typename FillType > |
![]() |
|
| Thread Tools | Search this Thread |
| |
Similar Threads for: "Syntax/Semantics for a C++ "Function Template"?" | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Getting Error "invalid syntax" in Python | kyosang | Software Development | 5 | 29-01-2010 10:53 PM |
| Getting the Error "Expression Syntax" in C++ | MarceloQuad | Software Development | 5 | 16-01-2010 06:35 PM |
| "older" inetres.adm template file | Jeff Clegg | Active Directory | 6 | 03-03-2009 12:10 AM |
| Moving from Novell: where's the "user template" object? | DMahalko | Active Directory | 2 | 27-01-2009 01:47 AM |
| how do i find "normal.dot template" | mjerh | MS Office Support | 12 | 11-12-2007 02:26 AM |