templates help

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • lallous

    templates help

    Hello,

    I would like to define a template as:

    template <class T, class R> void func(T &r)
    {
    r = (T)((R)r);
    }

    For example:
    double d;
    func<double, int>(d);
    this would do: (double)((int)d )

    1)Is this a good way to achieve this?
    I don't want to use any instance of "R" but just use it to cast.

    2)
    How can I set that "R" is by default a "long" type?
    It seems that <class T, class R = long> will only work w/ classes and not
    function templates.

    Regards,
    Elias


  • Victor Bazarov

    #2
    Re: templates help

    "lallous" <lallous@lgwm.o rg> wrote...[color=blue]
    > I would like to define a template as:
    >
    > template <class T, class R> void func(T &r)
    > {
    > r = (T)((R)r);
    > }
    >
    > For example:
    > double d;
    > func<double, int>(d);
    > this would do: (double)((int)d )
    >
    > 1)Is this a good way to achieve this?
    > I don't want to use any instance of "R" but just use it to cast.[/color]

    No, type casts cannot be used as a source of information for template
    type derivation. You could do

    template<class R, class T> void func(T &r)
    {
    r = T(R(r));
    }

    ...
    double d;
    ...
    func<int>(d); // no need to declare 'T', it will be
    // derived from the argument
    [color=blue]
    >
    > 2)
    > How can I set that "R" is by default a "long" type?
    > It seems that <class T, class R = long> will only work w/ classes and not
    > function templates.[/color]

    I am not sure what you mean by "will only work". Default template
    arguments are allowed for functions too.

    Victor


    Comment

    Working...