Messing recently with a multiple–dispatch solution in C++ / Boost / Loki environment I faced a number of challenges one of which was to implement a “delayed constructor” mechanism. Basically, this is a somehow known problem of binding values to constructors which isn’t solvable by boost::bind as there is no way to get an address of the constructor, but for which a solutions exists in boost::lambda::bind. Honestly, I didn’t look into there in deep. Instead I went for a short [maybe elegant] solution, compilable by any compiler supporting variadic templates (spirit of c++0x is already within our codes):
template <class TObject>
class DelayedConstructor
{
public:
template <class ...Args>
DelayedConstructor(Args ...args)
{
class ConstructHelper
{
public:
static TObject* DoConstruct(Args ...args)
{
return new TObject(args...);
}
};
m_funHelper = boost::bind(ConstructHelper::DoConstruct, args...);
}
TObject* operator()()
{
return m_funHelper();
}
protected:
boost::function<TObject*(void)> m_funHelper;
};
And here we use it:
class A
{
public:
A(int a, std::string str) { }
};
//Binding values to the constructor
DelayedConstructor<A> dc(21, "Good stuff!");
//Actually creating an object
A *pA = dc();
To me it looks very simple and rational. And keep in mind that it would work with any number of constructor arguments, which you don’t have to worry about at all. Just Use it.
But what’s left for a homework? Okay, let’s teach it to accept binding of only specific args. As we are used to do with regular functions.
P.S. But what is even more exciting is that as soon as c++0x lambdas come to play the solution of this problem would become trivial by using lambda factory function for desired class, which will eliminate usage of boot::bind.




The topic is continued here: http://blog.shandyba.com/2009/12/19/c-delayed-constructor-2-multi-level-approach/