• We just launched and are currently in beta. Join us as we build and grow the community.

C++ Template Functions

Krox

Laugh Commander
K Rep
0
0
0
Rep
0
K Vouches
0
0
0
Vouches
0
Posts
156
Likes
199
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
This source code is written in C++ and it is a simple code. The template functions are actually a bit easier to use than template classes, as the compiler can often deduce the desired type from the function's argument list. C++ templates can be used both for classes and for functions in C++.

Sample Code

The syntax for declaring a function is similar to that for a class.
template <

class

type>

type func_name(

type arg1,

arg2,

...

)

;

Now, when you actually use the add function, you can simply treat it like any other function because the desired type is also the type given for the arguments. This means that upon compiling the code, the compiler will know what type is desired.
int x =

add(

1

,

2

)

;

int x =

add<

int>

(

1

,

2

)

;

0134376331.jpg

For instance, to declare a function to add two values together using this syntax.
  1. template <

    class

    type>

    type add(

    type a,

    type b)
  2. {
  3. return

    a +

    b;
  4. }

It is also possible to have a class that has a member function that is itself a template, separate from the class template. Just like this.
  1. template <

    class

    type>

    class

    TClass
  2. {
  3. // constructors, etc

  4. template <

    class

    type2>

    type2 myFunc(

    type2 arg)

    ;
  5. }

    ;

The function myFunc is a function inside of a class, and when you actually define the function, you must respect this by using the template keyword twice. And avoid the following attempt to combine the two and it is wrong and it will not work, look at the syntax of badcode at the badcode source code sample.
  1. template <

    class

    type>

    // For the class
  2. template <

    class

    type2>

    // For the function
  3. type2 TClass<

    type>::

    myFunc

    (

    type2 arg)
  4. {
  5. // code
  6. }

  1. // bad code!
  2. template <

    class

    type,

    class

    type2>

    type2 TClass<

    type>::

    myFunc

    (

    type2 arg)
  3. {
  4. // ...
  5. }

 

452,292

323,341

323,350

Top