|
Boost : |
From: David Abrahams (dave_at_[hidden])
Date: 2002-08-20 13:20:30
From: "Andrew Koenig" <ark_at_[hidden]>
> Writing `new Target(src)' should work if you can write
>
> Target x(src);
>
> which you can't if Target is an enum type and src is an int value.
Okay, that makes sense. But then, it's as though the enum type has an
explicit constructor which accepts an int, right? So back to my original
problem: how can I use placement-new to explicitly convert one of these
things into memory I designate?
> dave> I guess I could use a named variable instead:
>
> dave> template <class Src, Target> int g(Src const& x)
> dave> {
> dave> Target t = x;
> dave> f(t);
> dave> return 0;
> dave> }
>
> dave> Is that the best answer?
>
> What about
>
> Target t(x);
Doesn't work for UDTs. Remember, it's supposed to work only if there's an
implicit conversion from Src to Target:
#include <memory>
template <class Target, class Src> int g(Src const& x)
{
Target t((x));
return 0;
}
enum E { e = 33 };
int z;
int y = g<std::auto_ptr<int> >(&z); // compiles
int x = g<E>(44.4); // doesn't
> dave> Finally, there's the issue of default construction. If I want to
> dave> generically declare a default-constructed object of type T, I
> dave> can't write:
>
> dave> T x;
>
> dave> since builtins (and I presume, enums) won't be initialized. I
> dave> can't write:
>
> dave> T x();
>
> dave> since that just declares a function. What can/should I write?
>
> You can write
>
> static T x;
>
> as long as you're not planning to clobber the value of x.
Uh, no thanks; I want a regular auto variable.
> For that matter, what about this?
>
> struct Temp {
> T x;
> Temp(): x() { }
> }
>
> Temp t;
>
> and then use t.x
Yeah, that's nasty, but it works.
-----------------------------------------------------------
David Abrahams * Boost Consulting
dave_at_[hidden] * http://www.boost-consulting.com
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk