A character that commits cannibalism will gain the aggravate monster intrinsic and lose 2–5 points of Luck. However, if you are an orc or a Caveman, cannibalism is considered natural for you, and you will not be penalized. As of NetHack 3.6.0, polymorphing into another form extends the cannibalism restriction to the new form, plus that of your base form. 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. Furthermore, polymorphing into a mind flayer and eating brains may be considered cannibalism. 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 such 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 base 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.
In SLASH'EM, a human eating a gibberling is considered cannibalism. Vampires are immune to cannibalism like orcs. SLASH'EM additionally does not contain the polymorph restrictions, and only explicitly eating the corpse of your base race is considered cannibalism.