C++ Template Function Partial Specialization
Introduction
In the template function implementation, however, for certain data types, we do not have a common template function to call to perform some tasks. We would have to end up with specializing the template function multiple times for those data types and there could be a lot of code duplications in the implementation.
In C++17, there are some features added so that the code duplications in this scenario could be removed. In this blog post, I would like to quickly talk about this in this blog post.
Example
In the following examples, we want to create a template function add for different data types. “Unfortunately”, for int and float, we were restrained to perform add using int_add and float_add, respectively. Then, in addition to the template function T add(T a, T b), we would also have to create the specialization functions for int add(int a, int b) and float add(float a, float b), both of which could have lots of code duplications with the template function T add(T a, T b). This is not good in terms of maintaining the code.
C++14
Before C++14, we could do nothing to remove the code duplications in this scenario.
1 |
|
1 | $ g++ add_cpp14.cpp -o add_cpp14 -std=c++14 |
C++17
Since C++17, because constexpr if becomes supported, we could implement the add in the following fashion and the code duplications were removed.
1 |
|
1 | $ g++ add_cpp17.cpp -o add_cpp17 -std=c++17 |
References
C++ Template Function Partial Specialization
https://leimao.github.io/blog/CPP-Template-Function-Partial-Specialization/