Namespaces
Variants
Views
Actions

Function template

From cppreference.com
 
 
C++ language
General topics
Preprocessor
Comments
Keywords
ASCII chart
Escape sequences
History of C++
Flow control
Conditional execution statements
Iteration statements
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

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