C++ 参数化构造函数在模板化 class

C++ parameterized constructor In a templated class

我最近开始学习 C++ 中的模板,我不确定是否需要包含 template <class T> 以实现参数化构造函数。

  template <class T>
  class A
  {    T num;

    //default constructor (parameterized)

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

当我为 constructor.But 添加 template<class T> 时,我得到一个错误阴影模板参数 < class T >,当我将其注释掉时它会起作用。

我想知道为什么我不需要为构造函数声明模板。

如果您确定需要模板构造函数,请为模板使用不同的参数名称:

template <class T>
  class A
  {   
    T num;

    //default constructor (parameterized)

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

否则,用于模板化构造函数的模板参数名称 T 将隐藏 class 模板声明中使用的名称。


如您在评论中所问"What are the occasions to use a templated constructor?"

适用于像

这样的情况
A<double> a(0.1f);

请注意,以上只是一个简单示例,不需要模板化构造函数。这只是为了演示模板化构造函数用于从与实例化中使用的类型不同的类型进行转换。


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

没有(或带有附加的)非模板化构造函数的模板 class 将简单地使用指定为 class 模板参数的 T 参数类型

template <class T>
  class A
  {   
    T num;

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

这是标准情况,大多数模板 class 不需要模板化构造函数或其他模板化函数。