【问题标题】:c++ typedef to fix template argsc ++ typedef修复模板参数
【发布时间】:2018-04-30 05:03:02
【问题描述】:

从 c++11 开始,我们可以这样做:

template<class A, class B> class C{};
template<class A> using D = C<A, int>;

所以DCB=int

typedef 在 c++03 中有没有办法做到这一点?

这不起作用:

template <class A> typedef C<A, int> D;

【问题讨论】:

    标签: c++ c++11 templates c++03


    【解决方案1】:

    不可能这么直截了当。 C++03 中唯一可以作为模板的是类和函数。类的好处是它们本身可以包含 typedef 作为成员。

    template<class A>
    struct D {
      typedef C<A, int> type;
    };
    

    所以现在D&lt;A&gt;::type 代表C&lt;A, int&gt;。这就是模板元编程中所谓的元函数。这很好,因为你可以在 C++03 中制作它。

    虽然 C++11 引入了别名模板,但这些模板需要新的别名语法,以及 using 关键字。像您一样尝试使用 typedef 也不是有效的 C++11。

    【讨论】:

    • 所以我们可以用D&lt;A&gt;::type d;来声明C&lt;A,int&gt; d;...太棒了!
    【解决方案2】:

    您可以通过继承在 C++03 上达到相似性:

    template<class A> D: public C<A, int> {};
    

    虽然D&lt;A&gt; 类型不完全是C&lt;A, int&gt;,但其行为将是相同的。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    相关资源
    最近更新 更多