Function template
From cppreference.com
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) | |||||||
- Template function declaration[1]
- 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
This section is incomplete Reason: partial 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) | ||||||||
- 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
- Implicit template arguments, deduced from the function arguments. No ambiguity can be present
This section is incomplete Reason: better explanation/example |
[edit] Example
This section is incomplete |
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 }