I've been reading recently about DI and IoC in C++. I am a little confused (even after reading related questions here on SO) and was hoping for some clarification.
It seems to me that being familiar with the STL and Boost leads to use of dependency injection quite a bit. For example, let's say I made a function that found the mean of a range of numbers:
template <typename Iter>
double mean(Iter first, Iter last)
{
double sum = 0;
size_t number = 0;
while (first != last)
{
sum += *(first++);
++number;
}
return sum/number;
};
Is this (i.e., using iterators instead of accessing the collection itself) dependency injection? Inversion of control? Neither?
Let's look at another example. We have a class:
class Dice
{
public:
typedef boost::mt19937 Engine;
Dice(int num_dice, Engine& rng) : n_(num_dice), eng_(rng) {}
int roll()
{
int sum = 0;
for (int i = 0; i < num_dice; ++i)
sum += boost::uniform_int<>(1,6)(eng_);
return sum;
}
private:
Engine& eng_;
int n_;
};
This seems like dependency injection. But is it inversion of control?
Also, if I'm missing something, can someone help me out? This seems to be the natural way to do things, so if that's all there is to Dependency Injection, why do people have a hard time using it?