Probably no use in your example, but there are some situations where it's difficult to deal with void
in template code, and I expect this rule helps with that sometimes. Very contrived example:
#include <iostream>
template <typename T>
T retval() {
return T();
}
template <>
void retval() {
return;
}
template <>
int retval() {
return 23;
}
template <typename T>
T do_something() {
std::cout << "doing something\n";
}
template <typename T>
T do_something_and_return() {
do_something<T>();
return retval<T>();
}
int main() {
std::cout << do_something_and_return<int>() << "\n";
std::cout << do_something_and_return<void*>() << "\n";
do_something_and_return<void>();
}
Note that only main
has to cope with the fact that in the void
case there's nothing to return from retval
. The intermediate function do_something_and_return
is generic.
Of course this only gets you so far - if do_something_and_return
wanted, in the normal case, to store retval
in a variable and do something with it before returning, then you'd still be in trouble - you'd have to specialize (or overload) do_something_and_return
for void.