template class instantiate without template parameter, automatictype deduction

Discussion in 'C++' started by Fei Liu, Oct 25, 2007.

  1. Fei Liu

    Fei Liu Guest

    Hello,
    We all know that a template function can automatically deduce its
    parameter type and instantiate, e.g.

    template <tpyename T>
    void func(T a);

    func(0.f);

    This will cause func<float> to be instantiated. The user does not have
    to explicitly call func<float>(0.f);

    However this line of thinking is broken when it comes to a template
    class constructor function, e.g.

    class A{
    int x;
    };

    template <typename T>
    class C{
    C(const T & t) : t(t) {}
    T t;
    };

    template <>
    class C<A> {
    C(const A & t) : t(t) {}
    A t;
    };


    int main(){

    A a;
    C c(a);
    }

    The above code can't be successfully compiled. One has to name the type
    returned from the constructor call to pick up the object. But what
    really distinguishes from normal function call is that even C(a) fails,
    compiler comlains missing template argument. The problem is sometimes
    you want automatic (auto) type deduction that a compiler can provide but
    you can't get it for constructor call.

    What's the current best practice to approach such kind of problem, i.e.
    automatic type deduction?

    Fei
    Fei Liu, Oct 25, 2007
    #1
    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. Neelesh

    Template parameter Deduction

    Neelesh, Nov 10, 2005, in forum: C++
    Replies:
    4
    Views:
    435
    John Carson
    Nov 10, 2005
  2. Fei Liu
    Replies:
    4
    Views:
    776
    Victor Bazarov
    Oct 26, 2007
  3. KD
    Replies:
    4
    Views:
    327
    Road.Tang
    Jun 20, 2008
  4. er
    Replies:
    5
    Views:
    1,272
  5. Replies:
    2
    Views:
    320
Loading...

Share This Page