Deduce function template argument

Discussion in 'C++' started by Ed, Aug 14, 2008.

  1. Ed

    Ed Guest

    Hi, guys,
    I met a issue that compiler can not deduce the template argument type
    from my code.


    template <typename Precision = float>
    struct Vector
    {
    typedef Precision scalar;

    Precision x;

    Vector(): x()
    {
    };

    Vector(Precision r)
    {
    x = r;
    }

    template <typename P>
    Vector(Vector<P>& r)
    {
    x = (Precision) r.x;
    }

    template<typename P>
    operator P()
    {
    return (P)x;
    };
    };

    template <typename P>
    void Hello(Vector<P> v)
    {
    };

    // use of the template
    int main()
    {
    Hello(1.0f); //Not work

    float f;
    Hello(f); //Not work

    return 0;

    }


    I want compiler to understand Hello(1.0f) is
    Hello( Vector<float>(1.0f) ).
    But compiler can't find this.

    Hoe can I make implicit constructor of Vector when the argument is
    float?

    Thanks!
    Ed, Aug 14, 2008
    #1
    1. Advertising

  2. Ed

    James Kanze Guest

    On Aug 14, 2:21 pm, "Alf P. Steinbach" <> wrote:
    > * Ed:


    > > template <typename P>
    > > void Hello(Vector<P> v)
    > > {
    > > };


    > > // use of the template
    > > int main()
    > > {
    > > Hello(1.0f); //Not work


    > > float f;
    > > Hello(f); //Not work


    > > return 0;
    > > }


    > > I want compiler to understand Hello(1.0f) is
    > > Hello( Vector<float>(1.0f) ).
    > > But compiler can't find this.


    Understandably. A float is not a vector.

    > > How can I make implicit constructor of Vector when the
    > > argument is float?


    > Templated arguments must match *exactly*.


    To tell the truth, this has nothing to do with templates. Even
    if he had a function "void Hello( Vector<float> v )", it
    wouldn't work. (Or maybe it would---he didn't show us the
    definition for Vector. But I can't imagine anything called
    Vector with a conversion constructor which would take a float.)

    --
    James Kanze (GABI Software) email:
    Conseils en informatique orientée objet/
    Beratung in objektorientierter Datenverarbeitung
    9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
    James Kanze, Aug 14, 2008
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    7
    Views:
    535
  2. George2

    template function argument deduce

    George2, Mar 11, 2008, in forum: C Programming
    Replies:
    0
    Views:
    369
    George2
    Mar 11, 2008
  3. Maik
    Replies:
    2
    Views:
    990
  4. nguillot
    Replies:
    5
    Views:
    530
  5. Nephi Immortal
    Replies:
    0
    Views:
    201
    Nephi Immortal
    Jan 26, 2013
Loading...

Share This Page