Need some experts validating a piece of code (functor)

Hello. I am in the middle of writing a series of classes to compute pretty much anything (distances, temperatures, times, speeds, etc.). My approach consists of a base Unit class where all units of measurement derive from. For higher level "dimensions" as I call them, the units can be the product of two or more simple units. I call this a CompoundUnit class. Each unit class knows its own conversion factor, so a compound unit can calculate the compound conversion factor from the conversion factors that compose it.

So there is a vector containing the unit object and the exponent the unit is raised to. I just need to for_each(). I have never coded a functor before, so here it is my first one. The thing is, I am unsure if I did it right. I am still writing other stuff and I am nowhere near compilation time. May I ask that you check it for me and let me know if I did it right?

Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class CompoundUnit : public Unit
{
	//Internal data.
protected:
	std::vector<UnitContext> _units;

	//Constructors
public:
	CompoundUnit() : Unit()
	{ }

	//Private functor to calculate the accumulated conversion factor.
private:
	class _ConvFactorF
	{
		//Internal Data
	private:
		double _accumFactor;

		//Constructor
	public:
		_ConvFactorF(double initialValue = 1.0) : _accumFactor(initialValue)
		{ }

		//Public Interface
	public:
		double GetAccumulatedConversionFactor() { return _accumFactor; }

		//Operator overloads
		void operator()(UnitContext const &uc)
		{
			_accumFactor *= pow(uc.GetUnit().GetConversionFactor(), uc.GetExponent());
		}
	};

	//Public Interface
	double GetConversionFactor()
	{
		_ConvFactorF f;
		std::for_each(_units.begin(), _units.end(), f);
		return f.GetAccumulatedConversionFactor();
	}
};
Ok, so no worries anymore. Today I was able to compile and perform a quick test. The functor object is copied when for_each() is called and then copied again in the return value of for_each(). :-( This means I had to change the code so I could intercept the return value to be able to get the conversion factor out of the functor.

Or, I could make it use an external variable by reference. But this is good for now.
Topic archived. No new replies allowed.