tags:

views:

93

answers:

1

Hello all,

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

+4  A: 

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).

Joe Gauterin
+1, but `boost::function<IConnection *()>` (note the pointer).
avakar
Good point. And you might instead want to return a smart pointer to be explicit about ownership.
Joe Gauterin
So fast reply. Thanks!
Zach
@avakar Isn't `IConnection*()` a function that returns a pointer to `IConnection`? Shouldn't it be `IConnection(*)()` instead?
FredOverflow
@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).
Joe Gauterin
@Joe Ah, so it's actually an `IConnection*(*)()`, right? :)
FredOverflow
@FredOverflow: 'IConnection*()' is fine - there really isn't a lot of difference between a function pointer and a function.
Joe Gauterin
Well, the shorter function syntax is just syntactic sugar for the longer function pointer syntax, right? :)
FredOverflow
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
Joe Gauterin