当我们需要提供模板参数来定义类时
when we need to provide template parameters to define a class?
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
是什么时才有效。有关更多详细信息,请参阅此相关问题。
相关文章:
- 如何使用宏根据参数定义不同的数据类型?
- 有没有办法根据命令行参数定义数组大小?运行时与编译时实例化?
- 为什么我需要将默认引用参数定义为 const 以便为其分配一个左值?
- 如何通过opencv中的程序参数定义特征类型?
- 确定是否有针对特定类型的参数定义的超载函数
- C 试图使用函数参数定义2D数组
- 是否可以为模板模板参数定义别名
- C++11:用容器参数定义函数(类似于基于范围的)
- C++-用类参数定义矢量大小
- 使用void* 参数定义纯虚函数的抽象基类.派生类匹配参数是指向某种类型的指针
- 如果我使用非常量参数定义那些,我是否仍然会获得默认的复制构造函数和运算符 =
- 使用参数定义的打印方法名称
- 如何根据类参数定义成员类运算符
- 如何为引用参数定义模板函数,为指针参数定义相同的函数
- boost::函数参数定义不起作用
- 如何基于不同的参数定义相同的宏函数
- 如何基于不同的参数定义相同的宏函数
- 将参数定义为未指定的模板类型
- C++模板,vector.size用于默认参数定义
- 如何为CamShift的矩形输入参数定义矩形变量