Function template

From cppreference.com
Jump to: navigation, search

Contents

[edit] Description

Templates allow generic function design that work on various types, without the need of rewriting it multiple times

[edit] Syntax

[edit] Declaration

template < template_arguments > function_declaration (1)
export template < template_arguments > function_declaration (2) (until C++11)
  1. Template function declaration[1]
  2. Exported template function declaration. The function body can be defined in a separate file[2]

[edit] Arguments

class identifier (1)
typename identifier (2)
integral_type identifier (3)
class identifier = type_name (4) (since C++11)
typename identifier = type_name (5) (since C++11)
integral_type identifier = const_expr (6) (since C++11)

1-2) Inside the function identifier can be used as a type

3) Inside the function identifier can be used as a constant

4-6) Default arguments

[edit] Specialization

template <> ret function_name < template_args > ( func_args ) body

Specialization changes the implementation of the template function for specific template parameters

[edit] Call

function_name < template_args > ( func_args ) (1)
function_name ( unambiguous_func_args ) (2)
  1. Explicit template arguments, if func_args don't match perfectly with the types as in the template declaration (with the given template_args) the usual casting will occur
  2. Implicit template arguments, deduced from the function arguments. No ambiguity can be present

[edit] Example

template<typename T>
struct S {
    template<typename U> void foo(){}
};
 
template<typename T>
void bar()
{
    S<T>s;
    s.foo<T>(); // error: < parsed as less than operator
    s.template foo<T>(); // OK
}

[edit] See Also

[edit] Notes

  1. The function body must be visible when the templated function is called
  2. This is very rarely implemented on compilers and should not be used
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox