当我们需要提供模板参数来定义类时

when we need to provide template parameters to define a class?

本文关键字:参数 定义 我们      更新时间:2023-10-16
template<typename T> class A // template parameterization
{
   private:
      T t;
   A(const T& v) : t(v) {}
};
class B
{
    template<typename T>
    B(const T& v)
    {
        std::cout << v << std::endl;
    }
};
// usage of A and B
A<int> a;
B      b(10);

问题>在什么情况下,我们必须提供模板参数才能定义类变量。

例如

如果类包含模板成员变量或???

谢谢

如果类是类模板,则必须提供模板参数才能创建实例。在您的示例中,class A 是类模板,而class B不是。

类模板:

template <typename T> class A {};

不是类模板:

class B { 
  // code may include function template, etc.
  // but the class itself is not a class template
};

在您的示例中,class B有一个模板构造函数,编译器可以使用该参数来确定要进行的专用化。所以在这种情况下,它生成一个等效于

B(const int&);

因为文字10是一个int.构造函数不像函数,因此这只有在编译器能够弄清楚T是什么时才有效。有关更多详细信息,请参阅此相关问题。