Add sparse matrix support for CachedFunction

There may be a way to reduce code duplication for all the "assert(0)" methods.