简体   繁体   English

为什么模板typedef是C ++(而不是C ++ 11)中的一个问题

[英]Why is template typedef an issue in C++ (not C++11)

In this question the OP asked for a solution to template typedef which is not possible in C++. 这个问题中 ,OP要求提供模板typedef的解决方案,这在C ++中是不可能的。 The OP also presented a solution themselves but did not like it: OP也提出了一个解决方案,但不喜欢它:

template<size_t N, size_t M>
class Matrix {
    // ....
};

// Problem - will not compile
typedef Matrix<N,1> Vector<N>;

// Solution
template <int N>
class Vector: public Matrix<N,1>
{ };

My question is, what advantage does the Helper::type solution give us over the OP's solution (assuming these classes are never meant to be used by a base pointer or new 'd as such)? 我的问题是, Helper::type 解决方案在OP的解决方案上给我们带来了什么好处(假设这些类永远不会被基指针或new 'd这样使用)? An empty class should carry no overhead in release (or does it?). 一个空类在释放时应该没有开销(或者是吗?)。 The only disadvantage I can see is that in debug builds you will have to expand the base class when debugging. 我能看到的唯一缺点是,在调试版本中,您必须在调试时扩展基类。

EDIT: In addition to the selected answer, see @Dani's answer who suggested that the inherited version would require constructors to be defined, which is an added inconvenience. 编辑:除了选定的答案,请参阅@ Dani的答案谁建议继承版本需要定义构造函数,这是一个额外的不便。

It's because constructors are not inherited (and in c++11 not by default). 这是因为构造函数不是继承的(并且在c ++ 11中不是默认的)。 So you have to copy all the non default constructs, even if you simply call the base class constructor in the implementation. 所以你必须复制所有非默认构造,即使你只是在实现中调用基类构造函数。

The point of typedef is to define a type alias. typedef的要点是定义一个类型别名。 A subclass is not a type alias - it is a new type. 子类不是类型别名 - 它是一种新类型。

For example, imagine some library function 例如,想象一下库函数

template<size_t N, size_t M>
Matrix<N, M> * createMatrix();

Now with helper type 现在有助手类型

Vector<3>::type * var = createMatrix<3, 1>();

is legal. 是合法的。
With inheritance 继承

Vector<3> * var = createMatrix<3, 1>();

is not. 不是。

Apart everyone taste on the syntax (that may be subjective) the main difference is that, by inhetirance, vector is actually another type that decays into matrix, while using an helper containing a typedef, vector is an alias of matrix (at least for what the partial specialization applies). 除了每个人对语法(可能是主观的)的品味之外,主要区别在于,通过inhetirance,vector实际上是另一种衰变为矩阵的类型,而使用包含typedef的帮助器,vector是矩阵的别名(至少对于什么部分专业化适用)。

The difference requires vector to redefine constructors (that are not inherited), or some potential pitfalls in case of operations defined in term of template specialization (with typedef, they will never be seen as "differnet") 差异需要向量来重新定义构造函数(不是继承的),或者在模板专业化定义的操作情况下存在一些潜在的陷阱(使用typedef,它们永远不会被视为“不同的”)

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

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