我正在尝试理解 C++ 中的模板类。首先,我想了解这一行的含义:
template <typename T, typename Ord = columns, typename All = abc::allocator<T,16> >
class matrix
其中列和分配器分别是在别处定义的结构和类(命名空间 abc 中的第二个)。让我烦恼的是它似乎有一个已经初始化的类型名。这是什么意思?当我想使用这个模板时,我是否也应该初始化 Ord 和 All 的类型名?
此外,还有这个唯一的构造函数:
explicit matrix(unsigned int rows = 0, unsigned int cols = 0, T init = T())
但是好像已经初始化过了。 init 是什么意思?
我向您保证,我查看了所有代码,但没有任何内容可以帮助您更好地理解。感谢您的关注。
编辑:谢谢大家的回答。只是一点点保证(我是 C++ 菜鸟):
int const& operator() operator()(unsigned int i, unsigned int j) const
这个方法意味着,当我们初始化类 foo 时,我们可以通过 foo()(1,2) 调用它,其中 i=1 和 j=2。我对吗?而这两个“const”指的是什么?
再次感谢!
最佳答案
template <typename T, typename Ord = columns, typename All = abc::allocator<T,16> >
class matrix
{
//...
};
这些是默认的模板参数,它们就像默认的函数参数一样工作 - 您可以指定它们,但如果您不指定它们,它们就是默认值。
您还可以看到函数默认参数的用法示例。
底线 - 以下所有行都是正确的:
matrix<int> a; // matrix<int, columns, abc::allocator<int, 16> >
matrix<int, rows> b; // matrix<int, rows, abc::allocator<int, 16> >
matrix<int, columns, abc::other_allocator<int, 32> > c; // obvious
matrix<int> a = matrix<int>(); // constructor called with 0, 0 and
// int() - default constructed T - in this case, int - as arguments
matrix<int> a(1, 2); // constructor called with 1, 2 and int() as arguments
matrix<int> a(1, 2, 100); // obvious
关于c++ - 模板中的奇怪类型名称和构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12999001/