【发布时间】:2018-04-30 05:03:02
【问题描述】:
从 c++11 开始,我们可以这样做:
template<class A, class B> class C{};
template<class A> using D = C<A, int>;
所以D 是C 和B=int。
typedef 在 c++03 中有没有办法做到这一点?
这不起作用:
template <class A> typedef C<A, int> D;
【问题讨论】:
从 c++11 开始,我们可以这样做:
template<class A, class B> class C{};
template<class A> using D = C<A, int>;
所以D 是C 和B=int。
typedef 在 c++03 中有没有办法做到这一点?
这不起作用:
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。
【讨论】:
D<A>::type d;来声明C<A,int> d;...太棒了!
您可以通过继承在 C++03 上达到相似性:
template<class A> D: public C<A, int> {};
虽然D<A> 类型不完全是C<A, int>,但其行为将是相同的。
【讨论】: