简体   繁体   English

模板化类中的C ++参数化构造函数

[英]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. 我最近开始学习C ++中的模板,但不确定我是否需要为参数化构造函数的实现包括template <class T>

  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. 当我为构造函数包含template<class T> <class T>时,我得到一个错误的影子模板parm <class T>,但是当我注释掉它时它可以工作。

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. 否则,用于模板化构造函数的模板参数名称T将覆盖类模板声明中使用的名称。


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 没有(或带有附加)非模板构造函数的模板类将简单地使用指定为类类型参数的T作为参数类型

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. 这是标准情况,大多数模板类不需要模板构造函数或其他模板函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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