Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2003-01-11 21:23:13


"Paul Mensonides" <pmenso57_at_[hidden]> writes:

> func( Y<int>::value ); // okay.
>
> // A temporary is created of type 'Y<int>::value_type'.
> // The address of that temporary is bound to
> // the const& parameter of 'func'.
> // 'func' is instantiated with 'T' == 'Y<int>::value_type'.
>
> func( Y<double>::value ); // okay.
>
> // A temporary is created of type 'Y<double>::value_type'.
> // The address of that temporary is bound to
> // the const& parameter of 'func'.
> // 'func' is instantiated with 'T' == 'Y<double>::value_type',
> // which is a *different* instantiation of 'func'.
> // (i.e. unnecessary code bloat)
>
> /* ----
>
> problem:
>
> Usage causes template functions to be instantiated multiple times for no
> reason. IMO, this is *way* worse than the storage necessary to hold the
> static constants.
>
> solution:
>
> There is no non-intrusive solution. It must be cast at the call site to a
> common type (such as 'int' or 'bool') in order to avoid replicated template
> instantiation.
>
> ---- */

Of course, you can use the first solution with enums as well:

    template <class T, T N>
    struct integral_c
    {
       enum value_type { value = N; };
    };

    template<class T> struct Y
       : integral_c<int,10> {};

Now Y<int>::value and Y<double>::value have the same type. Of course,
you will probably want some additional tools in integral_c<T,N>, like
an explicit conversion to an rvalue of type T.

-- 
                       David Abrahams
   dave_at_[hidden] * http://www.boost-consulting.com
Boost support, enhancements, training, and commercial distribution

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