I am deep into a new project which I address with a bunch of templates and specializations of them. Now, after a day without programming, I find myself asking whether it is really worth the extra lines of code.
The question is: What are the advantages of specialization?
Is this:
template <int i> class A {};
template <> class A <1> { void foo() {/* something */} };
template <> class A <2> { void foo() {/* something else*/} };
template <> class A <3> { void foo() {/* even different*/} };
In any way better (faster execution) than
template <int i> class A {
void foo() {
if (i==1) {/* something */}
else if (i==2) {/* something else*/}
else if (i==3) {/* even different*/}
}
};
?
Edit:
The code is part of a library to be used by others. I am using gcc 4.6.3 but in the end the code will be used with different compilers.
Edit:
These two pieces of code result in identical binaries using gcc 4.6.3. I cannot test the full case as my actual code is far from being usable. It really seems to be a matter of principle, versatiliy, reusability, maintanability etc...
Speed is not the primary issue here, but extensibility is.
Specialization has the advantage that you make it easier for clients of your code to add new overloads of foo()
. Suppose you later decide to add new behavior for i=4
: in the first approach, you simply add a new specialization; in the second version, you need to modify the function foo()
. If you have released your library in binary form, clients will not be happy.
The preference of the specialization approach to the second one is a manifestation of the Open/Closed Principle: code should be open for extension, closed for modification.