|
Boost : |
From: Arkadiy Vertleyb (vertleyb_at_[hidden])
Date: 2002-11-02 22:27:21
Rene Rivera wrote:
> How 'bout this...
>
> #include <cassert>
>
> class some_class
> {
> public:
> some_class() : number(0) { }
> int number;
> };
>
> class another_class
> {
> public:
>
> template <typename some_type>
> struct some_type_defer { typedef some_type t_; };
>
> template <typename some_type>
> typename some_type_defer<some_type>::t_ & field()
> {
> static some_type test_object;
> return test_object;
> }
> };
>
> int main(int argc, char** argv)
> {
> some_class c_;
> another_class x_;
>
> c_.number = 1;
> c_ = x_.field<some_class>();
> assert(c_.number == 0);
>
> c_.number = 2;
> x_.field<some_class>() = c_;
> assert(x_.field<some_class>().number == 2);
> }
>
> ...It works with g++ 2.96(RedHat) and 3.2.
Do I understand correctly that if you use
template <typename some_type>
some_type & field()
{
static some_type test_object;
return test_object;
}
this does not work, but if you change it to be:
template <typename some_type>
typename some_type_defer<some_type>::t_ & field()
{
static some_type test_object;
return test_object;
}
it works fine? This is scary, isn't it? :o)
> Aren't templates fun... and twisted ;-)
They sure are. Reminds me of science fiction movies, where robots start
leaving their own lives, independent of their creators :o). Template
meta-programming was DISCOVERED (!!!) Anybody knows who discovered it?
One more option would be to use:
tuple.field(column()); // create a temp object and pass by reference
Would compilers optimize away unnecessary temporary object creation?
Arkadiy
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk