简体   繁体   中英

C++ parameterized constructor In a templated class

I recently start learning templates in C++ and I am not sure if I need to include template <class T> for my implementation of a parameterized constructor.

  template <class T>
  class A
  {    T num;

    //default constructor (parameterized)

    template <class T>//getting error
    A(T value)
    { num=value;}
  } 

I get an error shadow template parm < class T > when I include template<class T> for the constructor.But it works when I comment it out.

I am wondering why I dont need to declare the template for the constructor.

If you're sure you need a templated constructor function, then use a different parameter name for the template:

template <class T>
  class A
  {   
    T num;

    //default constructor (parameterized)

    template <class U>
                 // ^
    A(U value)
   // ^
    { num=value;}
  };

Otherwise the template parameter name T used for the templated constructor function would shadow the name used in the class template declaration.


As you are asking in a comment "What are the occasions to use a templated constructor?"

It's for cases like

A<double> a(0.1f);

Note the above is just a simple example, and wouldn't need a templated constructor. It's just to demonstrate the templated constructor is used for conversion from types that are different from the type used in the instantiation.


"I am wondering why I dont need to declare the template for the constructor."

A template class without (or with an additional) non-templated constructor would simply use the T specified as class template parameter for the parameter type

template <class T>
  class A
  {   
    T num;

    A(T value)
   // ^
    { num=value;}
  };

This is the standard case, most template classes don't need templated constructor or other templated functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM