views:

107

answers:

1

Is it a common pattern/idiom to use free functions as pseudo-constructors to avoid having to explicitly specify template parameters?

For example, everyone knows about std::make_pair, which uses its parameters to deduce the pair types:

template <class A, class B>
std::pair<A, B> make_pair(A a, B b)
{
  return std::pair<A, B>(a, b);
}

// This allows you to call make_pair(1, 2),
// instead of having to type pair<int, int>(1, 2)
// as you can't get type deduction from the constructor.

The STL also makes heavy use of this in <functional> (bind1st, not1, ptr_fun, etc...)

I find myself using this quite often, so I was just wondering if many other people use it, and if there is a name for this pattern?

+6  A: 

Apparently it's called "Object Generator". See "More C++ Idioms" and "Boost" on this topic.

I personally find it very useful and use it alot.

Also, I think one might see expression templates as a special form of object generators, since all they do is construct complex types by means of operand types and data you normally could specify also manually. Except, they are calling the generators implicitly

a + b + c =>
  Add<Add<A, B>, C>(...)
Johannes Schaub - litb
I certainly prefer "object generator", because "generator function" already has a mathematical meaning.
Peter Alexander
@Poita_ agreed. I see now it's a well known name and part of the boost docs, so i think i will call them object generators too :)
Johannes Schaub - litb
I love this idiom, and in combination with `auto` you can make complex template constructions without ever actually explicitly specifying a template parameter.
GMan
In programming competitions, I sometimes use a macro `#define create(x, y) typeof(y) x = (y)` Very ugly, but works :)
Peter Alexander
@Poita_: Wasn't that "generating function"?
tiftik
@tiftik, ah yes, you are right -- but they still sound too similar for my liking :)
Peter Alexander