Search code examples
c++c++11templatestemplate-specialization

Specializing function templates in C++


I am familiar with class specialization but came across this piece of code which I believe is function specialization

A:
template <bool include_negatives>
int average(int* array, int len) {
....
}

I could rewrite the above as this C . I know that I am specializing a class so I need to provide B. My question is what is happening in A. Why does that not need a generic type since its being specialized.

B:
template<typename t>
int average(){

}

C:
template<>
int average<bool>(){
  ...
}

My question is why does the


Solution

  • include_negative is a non type template parameter using the integral type bool.

    There is no specialization in this case. The template parameter has a fixed type that serves as a placeholder for a constexpr value. In the aforementioned link you'll see that "A non-type template parameter must have a structural type, which is one of the following types (optionally cv-qualified, the qualifiers are ignored):"

    • lvalue reference type (to object or to function);
    • an integral type;
    • a pointer type (to object or to function);
    • a pointer to member type (to member object or to member function);
    • an enumeration type;
    • std::nullptr_t;
    • a floating-point type;
    • a literal class type (...)