Airlines are allowed to calculate center of gravity by using legally defined assumptions for what the weight of each person will be. It might vary between countries, but normally there are numbers for men, women, children under 12, and infants up to 2 years old. These weights can be added to in the winter to account for extra clothing in some regions. All the information is sent into a computer thats then says if they are a go or not.
In theory there are much better was this could be done, for example adding a weighing system to each leg of the landing gear would allow precise control. In the end though things move around in flight and the baggage handlers aren't exactly known for their careful placement of luggage, best you will probably get is put more stuff that way.
In flight would seem a little trickier, however most aircraft record data such as angle of attack, flight speed, ambient pressure, and control surface position. Using a spreadsheet generated from models, an aircraft could easily determine its approximate cg by comparing how much lift it should be producing, where the center of pressure on the wing should be, and how much the horizontal stabilizer is pushing downwards.