A character that eats a corpse, tin or egg of the same species as them - including their current form if polymorphed - will gain the aggravate monster intrinsic and lose 2–5 points of Luck. This includes eating brains as a mind flayer. However, if you are an orc or a Caveman, cannibalism is considered natural for you, and you will not be penalized. Contracting lycanthropy will further extend the cannibalism restriction to beasts similar to your wereform even when you're still in your original form, but not to lycanthropes of your type.
Whether you are exempt from cannibalism rules altogether depends solely on your base form: orcish heroes and Cavemen will never be affected by cannibalism, but a human polymorphing into an orc could not safely eat orc or human corpses. If you polymorph into a monster with a digestion attack, using that attack is not considered cannibalism.
Cannibalism is generally a bad idea - while the aggravate monster intrinsic can be dealt with, the Luck penalty will take significant time to recover from, and eating corpses from your own race is avoidable enough that it is mostly not worth considering. Dwarves and gnomes can readily identify members of their race via glyph and/or monster name, as can elves; Human (monster attribute) characters will have some slight difficulty due to sharing a glyph (@) with elves. Anything represented by an @ that isn't obviously an elf is human—this includes werecreatures and doppelgangers, but not Medusa (who should not be eaten regardless, lest you turn to stone). The Keystone Kops (represented by a K) count as humans, and are the only non-undead monsters that use a different glyph to do so.
Human characters who are not Cavemen should only use blessed tins of nurse meat to fully restore their HP in emergencies, where being a live cannibal is preferable and easier to recover from than dying with a "clean" conscience.
SLASH'EM additionally does not contain the polymorph restrictions, and only explicitly eating the corpse of your base race is considered cannibalism.
In dNetHack, if you are a non-cannibalistic race or role and have a high alignment record, you have a wisdom-based chance to be warned if you are eating something of the same race as you. ("You feel a deep sense of kinship to <foo>! Eat anyway?")