How to create a "Looping" Cast. C++

If anyone has a better way to do this or just some improvements please share them, or if you know how to make this it’s own public function that can be used by any class.