C++ 模板 typedef
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2795023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ template typedef
提问by Notinlist
I have a class
我有一堂课
template<size_t N, size_t M>
class Matrix {
// ....
};
I want to make a typedef
which creates a Vector
(column vector) which is equivalent to a Matrix
with sizes N and 1. Something like that:
我想typedef
创建一个Vector
(列向量),它相当于一个Matrix
大小为 N 和 1 的a 。类似这样的东西:
typedef Matrix<N,1> Vector<N>;
Which produces compile error. The following creates something similar, but not exactly what I want:
这会产生编译错误。以下创建了类似的东西,但不完全是我想要的:
template <size_t N>
class Vector: public Matrix<N,1>
{ };
Is there a solution or a not too expensive workaround / best-practice for it?
是否有解决方案或不太昂贵的解决方法/最佳实践?
回答by GManNickG
C++11 added alias declarations, which are generalization of typedef
, allowing templates:
C++11 添加了别名声明,它是 的泛化typedef
,允许模板:
template <size_t N>
using Vector = Matrix<N, 1>;
The type Vector<3>
is equivalent to Matrix<3, 1>
.
该类型Vector<3>
等效于Matrix<3, 1>
.
In C++03, the closest approximation was:
在 C++03 中,最接近的近似值是:
template <size_t N>
struct Vector
{
typedef Matrix<N, 1> type;
};
Here, the type Vector<3>::type
is equivalent to Matrix<3, 1>
.
在这里,类型Vector<3>::type
等效于Matrix<3, 1>
。