[cpp] keep stack in visit_type to avoid infinite recursion (closes #3024)