Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function template specialization importance and necessity

I read C++ Primer, and it says function template specialization is an advanced topic, but I am totally lost. Can anybody offer an example why function template specialization is important and necessary?

Why don't function templates support partial specialization while class templates do? What's the underlying logic?

like image 346
skydoor Avatar asked Feb 04 '10 03:02

skydoor


People also ask

What is the importance of function templates?

Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type.

What is template specialization used for?

This is called template specialization. Template allows us to define generic classes and generic functions and thus provide support for generic programming. Generic programming is an approach where generic data types are used as parameters in algorithms so that they work for variety of suitable data types.

What is explicit template specialization?

Explicit (full) specializationAllows customizing the template code for a given set of template arguments.

What do you mean by functions templates explain?

Function templates are similar to class templates but define a family of functions. With function templates, you can specify a set of functions that are based on the same code but act on different types or classes.


1 Answers

Your question of why functions do not support partial specialization can be answered here. The code below shows how to implement the different specializations.

template<typename T>
bool Less(T a, T b)
{
    cout << "version 1 ";
    return a < b;
}
// Function templates can't be partially specialized they can overload instead.
template<typename T>
bool Less(T* a, T* b)
{
    cout << "version 2 ";
    return *a < *b;
}

template<>
bool Less<>(const char* lhs, const char* rhs)
{
    cout << "version 3 ";
    return strcmp(lhs, rhs) < 0;
}

int a = 5, b = 6;

cout << Less<int>(a, b) << endl;
cout << Less<int>(&a, &b) << endl;
cout << Less("abc", "def") << endl;
like image 148
Jagannath Avatar answered Nov 15 '22 01:11

Jagannath