【问题标题】:Template Metaprogramming for concatenation of compile-time sequences用于连接编译时序列的模板元编程
【发布时间】:2015-02-22 15:50:53
【问题描述】:

所以我一直在用我自己的序列类在 c++ 中尝试编译时序列,但我遇到了急切模板实例化的问题,或者至少我认为就是这样。

template <typename SeqA, typename SeqB, int... Items>
class Concat 
    : public std::conditional<SeqA::is_empty() && SeqB::is_empty(),
                 Seq<Items...>, 
                 typename std::conditional<SeqA::is_empty(),
                     typename Concat<SeqA, typename SeqB::Tail, Items..., SeqB::Head>::type, 
                     typename Concat<typename SeqA::Tail, SeqB, Items..., SeqA::Head>::type
                 >::type
              >
{
};

我从编译器收到一条错误消息,指出

main.cpp: In instantiation of ‘Concat<Seq<2, 4, 6, 8, 10>, Seq<>, 1, 3, 5, 7, 9>’:
main.cpp:75:7:   recursively instantiated from ‘Concat<Seq<2, 4, 6, 8, 10>, Seq<3, 5, 7, 9>, 1>’
main.cpp:75:7:   instantiated from ‘Concat<Seq<2, 4, 6, 8, 10>, Seq<1, 3, 5, 7, 9> >’
main.cpp:99:52:   instantiated from here
main.cpp:75:7: error: no type named ‘Tail’ in ‘class Seq<>’
...

concat 类的工作原理是从第一个非空序列中抓取一个项目并将其附加到它自己的可变参数中。当两个集合都为空时,它返回一个以元素作为序列的集合,但错误消息让我感觉编译器将实例化 std::conditional 的两个部分,而不管真值如何。有没有办法解决这种行为?

【问题讨论】:

    标签: c++ templates template-meta-programming


    【解决方案1】:

    这太复杂了。这是我写Concat的方式:

    template <int...> class Seq;
    template <typename SeqA, typename SeqB> class Concat;
    template <int... Ints1, int... Ints2>
    class Concat<Seq<Ints1...>, Seq<Ints2...>>
    {
        using type = Seq<Ints1..., Ints2...>;
    };
    

    是的,std::conditional 需要评估其所有参数;不会发生短路。这可以通过另一个间接层来解决,就像在编程中一样。

    【讨论】:

    • 这比我想象的要好得多。
    猜你喜欢
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 2012-11-03
    • 2016-11-26
    相关资源
    最近更新 更多