How do I make an object only visible when it is in front of another specific object?
I believe this is impossible to do with materials.  But I was able to get this effect with some render layers and compositing.



First put the front object in a separate layer than the rest of your scene.  Then set up two render layers, one which renders all the layers, and one which excludes the layer with the front object.  (Check out my explanation of excluding layers here).



Next give the back object a different pass index under the Object properties panel > Relations rollout.  And make sure that you have the Object Index, and Z passes enabled on your render layers (see above).



Then use the following node setup to composite the two layers together.



The Less Than node compares the z-depths of the two render layers to find where the animated Suzanne is in front of the other one, the Add and Greater Than nodes work as a logical AND operator between this and the ID mask of the back Suzanne.  So the mix node will grab the "main" render layer iff the animated Suzanne is closer to the camera and overlaps the other one in the rendered image.  Which, I believe, is the effect you desire.