Boost logo

Boost :

From: Fernando Cacciola (fernando_cacciola_at_[hidden])
Date: 2003-09-11 09:47:29


Eric Friedman <ebf_at_[hidden]> wrote in message news:bjp6nq$ahg$1_at_sea.gmane.org...
> Fernando,
> [snip]
> > you can initialize an optional constructing its contained
> > value directly in place instead of copying an existing object:
> >
> > struct A
> > {
> > A ( int a, std::string s ) ;
> > } ;
> >
> > boost::optional<A> opt( boost::in_place(1234,"Hellow world!") ) ;
> >
> > As you can see, the "factory expression" : in_place(...) does not
> > need the optional's value_type (A in this case), so the
> > syntax is terse.
>
> Unfortunately this syntax will not work for variant. For example:
>
> struct B
> {
> B(int a, std::string s);
> };
>
> boost::variant<A,B> var(
> boost::in_place(1234,"Hello world!") // A or B?
> );
>
Oh, good point.

> I'm guessing we could both have our desired syntax if there were also
> boost::in_place overloads taking an explicit template argument.
>
> Does this seem feasible to you?
>
>
> Thanks,
> Eric
>
> P.S. Really though, I'm not sure if the following would be so terrible:
>
> boost::optional<A> opt(
> boost::in_place<A>(1234,"Hello world!")
> );
>
> After all, it's not so different from:
>
> boost::optional<A> opt(
> A(1234,"Hello world!")
> );
>
OK, I see two choices here.
If in_place<> uses its first template parameter to designate the target
type, then it will be used exactly as you show above and then it could be
adopted by variant as is.
OTOH, it might be a bit annoying to force users to specify the target type
all the time when it is not really necessary.
I'm not sure if this would be a real problem though, since after all,
as you say, it's ordinary to carry the target type along with its
ctor arguments. It can even be argued that the explicit form is more
expressive as it explicitely designates the object that will be constructed
with those parameters.
A shortcoming of this explicit form is that currently, the expression
in_place(x,y,z) is an object which is untied to any particular target
type, so I figure that it could be used as a form of currying
that can be used to close construction expressions of all types having the
same constructor signature. That is, it can be reused with different
types. Anyway, this is out of the scope of the utility so we might just
disregard it.

Alternatively, we could have two flavours of this:

in_place(x,y,z) -> x,y,z are constructor parameters for any type.
typed_in_place(T,x,y,z) -> are constructor parameters for the type T.

Notice that if we want to use the same function for both cases
there must be a way to tell whether the first parameter is the target type
or the first contructor argument type.

btw, optional<> could support both forms, for instance.

What do you think?

Fernando Cacciola


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk