1

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++?

Zach
  • 5,715
  • 12
  • 47
  • 62

1 Answers1

4

Use either std::tr1::function<IConnection*()> or boost::function<IConnection*()> as the equivalent of Func<IConnection>.

When you come to assign the function, you'll need to bind a object and a function together;

f.CreateConnectionFunc = this.CreateConnection;

would become

f.CreateConnectionFunc = std::tr1::bind(&Program::CreateConnection,this);

(That assumes CreateConnection is not a static function - your example code doesn't get its statics correct, so it's difficult to tell exactly what you meant).

JoeG
  • 12,994
  • 1
  • 38
  • 63
  • 1
    +1, but `boost::function` (note the pointer). – avakar May 21 '10 at 09:26
  • Good point. And you might instead want to return a smart pointer to be explicit about ownership. – JoeG May 21 '10 at 09:29
  • @avakar Isn't `IConnection*()` a function that returns a pointer to `IConnection`? Shouldn't it be `IConnection(*)()` instead? – fredoverflow May 21 '10 at 10:21
  • @FredOverflow: `IConnection*()` is a function that returns a pointer to `IConnection`. `IConnection(*)()` is a pointer to a function that that returns an `IConnection` by value. `IConnection*()` is what's needed here, as returning an interface by value will lead to object slicing (or compile time errors). – JoeG May 21 '10 at 10:51
  • @FredOverflow: 'IConnection*()' is fine - there really isn't a lot of difference between a function pointer and a function. – JoeG May 21 '10 at 15:29
  • Well, the shorter function syntax is just syntactic sugar for the longer function pointer syntax, right? :) – fredoverflow May 21 '10 at 15:36
  • Functions and function pointers are different, but functions implicitly convert into function pointers. The answers to this question go into the details: http://stackoverflow.com/questions/2795575/how-does-dereferencing-of-a-function-pointer-happen – JoeG Jun 03 '10 at 07:32