So, what's the rule of thumb here?
I just worked it out myself, so I could be wrong, but it looks to me like you want to:
1. Take the cost of the unit that you plan to spam
2. Figure out the Hammer multipliers and add them together (base Hammers = 1, Forge = 0.25, Factory = 0.25, Power with a Factory = 0.5, Bureaucracy = 0.5, Heroic Epic = 1.0, Military Academy = 0.5, DryDock = 0.5)
3. Divide the cost of the unit by the total Hammer multipliers
4. Floor aka truncate the result
5. Ensure that your City produces equal to or less than this number of base Hammers (not counting overflow Hammers) per turn
If you can set your City up in that manner, then the only lost Hammers from overflow capping that you could see is when you build your first unit, should you happen to have started with a larger overflow of Hammers than the "charged" cost of the unit.
So, again, let's take our Swordsman example:
1. Cost = 40 Hammers
2. base Hammers + Forge + Heroic Epic = 1 + 0.25 + 1 = 2.25
3. 40 / 2.25 = 17.7777
4. floor(17.7777) = 17
5. Stop the City from making 20 base Hammers and switch the squares work to make 17 or less base Hammers
Then, when you go to build the first Swordsman, try not to have more overflow Hammers going into the build item than can be used. Thus, if we followed step 5 properly, we'd be okay with up to 18 overflow Hammers coming in on that first turn of building a Swordsman (since 18 Hammers would get "used up" to create the next Swordsman--since we cannot use only a partial base Hammer in its construction, allowing all 17 of our to-be-made-this-turn base Hammers to overflow).