In C#, I use Func to replace Factories. For example:
class SqlDataFetcher
{
public Func<IConnection> CreateConnectionFunc;
public void DoRead()
{
IConnection conn = CreateConnectionFunc(); // call the Func to retrieve a connection
}
}
class Program
{
public void CreateConnection()
{
return new SqlConnection();
}
public void Main()
{
SqlDataFetcher f = new SqlDataFetcher();
f.CreateConnectionFunc = this.CreateConnection;
...
}
}
How can I simulate the code above in C++?
Use either
std::tr1::function<IConnection*()>orboost::function<IConnection*()>as the equivalent ofFunc<IConnection>.When you come to assign the function, you’ll need to bind a object and a function together;
would become
(That assumes
CreateConnectionis not a static function – your example code doesn’t get itsstaticscorrect, so it’s difficult to tell exactly what you meant).