C++ typedef 修复模板参数
c++ typedef to fix template args
从 c++11 开始,我们可以这样做:
template<class A, class B> class C{};
template<class A> using D = C<A, int>;
所以 D
是 C
和 B=int
。
在 c++03 中 typedef
有没有办法做到这一点?
这不起作用:
template <class A> typedef C<A, int> D;
不可能这么简单。在 C++03 中唯一可以作为模板的是 类 和函数。 类 的好处是它们本身可以包含 typedef
作为成员。
template<class A>
struct D {
typedef C<A, int> type;
};
所以现在 D<A>::type
代表 C<A, int>
。这就是模板元编程中所谓的元函数。它很好,因为你可以在 C++03 中实现它。
虽然 C++11 引入了别名模板,但它们需要新的别名语法,以及 using
关键字。 typedef
的尝试,就像你所做的那样,也不是有效的 C++11。
您可以通过继承在 C++03 上达到相似性:
template<class A> D: public C<A, int> {};
虽然 D<A>
类型不准确 C<A, int>
,但其行为是相同的。
从 c++11 开始,我们可以这样做:
template<class A, class B> class C{};
template<class A> using D = C<A, int>;
所以 D
是 C
和 B=int
。
在 c++03 中 typedef
有没有办法做到这一点?
这不起作用:
template <class A> typedef C<A, int> D;
不可能这么简单。在 C++03 中唯一可以作为模板的是 类 和函数。 类 的好处是它们本身可以包含 typedef
作为成员。
template<class A>
struct D {
typedef C<A, int> type;
};
所以现在 D<A>::type
代表 C<A, int>
。这就是模板元编程中所谓的元函数。它很好,因为你可以在 C++03 中实现它。
虽然 C++11 引入了别名模板,但它们需要新的别名语法,以及 using
关键字。 typedef
的尝试,就像你所做的那样,也不是有效的 C++11。
您可以通过继承在 C++03 上达到相似性:
template<class A> D: public C<A, int> {};
虽然 D<A>
类型不准确 C<A, int>
,但其行为是相同的。