Introduce templates to loop queries looking for singletons.
Several loop queries look for a singleton by finding all instances and then
returning whether there is 1 instance or not. This can be improved by
stopping the search after 2 have been found. Introduce templates for
these functions to special-case such usage.
There is no intended functional change.