Flatten arbitrary structures using a template