【问题标题】:Infinite recursive template instantiation when using Clang while GCC works fine?在 GCC 工作正常时使用 Clang 时无限递归模板实例化?
【发布时间】:2016-10-22 05:25:56
【问题描述】:

以下 c++ 代码的目的是将三元运算符 (?:) 包装在一个单独的函数中,这将有助于稍后构建语法树。

在看真正的 c++ sn-p 之前,让我们快速看一下它在伪代码中的作用:

bool recursive(bool v) {
    return v ? v : recursive(v);
}
int main() {
    bool r = recursive(true)
}

不幸的是,当三元运算符 (?:) 被包装在模板函数中时,Clang 在终止递归时遇到问题:

/****************** DECLARATIONS ******************/
template<typename T>
constexpr T
recursive(T t);

struct IfCase {
    template<typename T>
    constexpr T
    operator()(T t) const;
};

struct ElseCase {
    template<typename T>
    constexpr T
    operator()(T t) const;
};

#if defined(WORKS)
    static constexpr bool
    if_then_else_return(bool b, IfCase const& ic, ElseCase const& ec, bool x);
#else
    template<typename T, typename IfFunctor, typename ElseFunctor>
    static constexpr T
    if_then_else_return(T b, IfFunctor const& ic, ElseFunctor const& ec, T x);
#endif

/****************** DEFINITIONS ******************/
template<typename T>
constexpr T
IfCase::operator()(T t) const {
    return t; 
}

template<typename T>
constexpr T
recursive(T t) {
    return if_then_else_return(t, IfCase{}, ElseCase{}, t);
}

template<typename T>
constexpr T
ElseCase::operator()(T t) const {
    return recursive(t); 
}

#if defined(WORKS)
    constexpr bool
    if_then_else_return(bool b, IfCase const& ic, ElseCase const& ec, bool x) {
        return b ? ic(x) : ec(x);
    }
#else
    template<typename T, typename IfFunctor, typename ElseFunctor>
    constexpr T
    if_then_else_return(T b, IfFunctor const& ic, ElseFunctor const& ec, T x) {
        return b ? ic(x) : ec(x);
    }
#endif


/****************** CALL ******************/

int main() {
    constexpr auto r = recursive(true);
}

构建结果:

GCC (4.9.2) 编译两个变体都没有错误,但 Clang (3.5 到 3.8) 失败并显示以下错误消息:

main.cpp:56:14: fatal error: recursive template instantiation exceeded maximum depth of 256
                return b ? ic(x) : ec(x);
                           ^
/*** the next error messages for lines 64, 38 and 56 are repeated several times ***/

main.cpp:56:22: note: in instantiation of function template specialization 'ElseCase::operator()<bool>' requested here
                return b ? ic(x) : ec(x);
                                   ^
main.cpp:38:9: note: in instantiation of function template specialization 'if_then_else_return<bool, IfCase, ElseCase>' requested here
        return if_then_else_return(t, IfCase{}, ElseCase{}, t);
               ^
main.cpp:64:21: note: in instantiation of function template specialization 'recursive<bool>' requested here
        constexpr auto r = recursive(true);
                           ^
1 error generated.

但是为什么呢?如何重写这段代码,让 Clang 不再抱怨?

非常感谢您。

编辑 1

  • 我缩短了编译器消息,希望能提高其可读性。如需完整的回溯,请查看上面提供的 Coliru 链接。

  • 删除 constexpr 说明符将解决此 Clang 错误。但这也会减少功能,因此不是一种选择。

【问题讨论】:

  • 请在 Coliru here (reg. function)here (tmpl. function) 找到 GCC 的代码和构建结果。
  • 请使用minimal reproducible example 示例,走开。在这个问题的情况下,如果您将问题从产生错误的 one 函数中减少为 one 错误,那么帮助您会更容易。
  • 感谢您的提示!如果我删除constexpr,问题就消失了,但这也会减少功能。如果我删除#ifdef 等。恕我直言,很难理解我对 reg 的意思。函数tmpl。功能,但如果有帮助,我可以删除它们。如果没有声明和定义之间的分离,我会遇到 GCC 编译错误。你到底想到了什么?
  • 你不需要显示所有的错误信息。如果其中一个声明/定义导致错误,只需将其用作示例,而不是全部使用。当然,不要更改代码的功能/目的或使用糟糕的编程实践;这不是我的建议。尝试使用最少量的代码进行编译,从而以最能代表您的问题的方式导致错误。
  • 可能是您使用的代码是最少需要的,但有些错误是完全重复的。

标签: c++ templates gcc clang ternary-operator


【解决方案1】:

一种解决方法是通过向参与递归的构造的模板参数添加一个计数器来限制递归,在递归调用时更新计数器,并使用部分特化来终止递归。

我对您的程序进行了以下更改:

  • IfCaseElseCaseIfCase 仅用于对称)更改为模板类,而不是具有模板成员函数的常规类。这允许部分专业化。

  • ElseCaserecursive() 添加了一个整数计数器模板参数。

  • ElseCase 中调用recursive() 时增加计数器。

  • 在不进行递归调用的任意递归深度处创建了 ElseCase 的部分特化。应调整最大深度以避免 clang++ 限制。

代码如下:

#include <cassert>

/****************** DECLARATIONS ******************/
template<typename T, int N = 0>
constexpr T
recursive(T t);

template<typename T>
struct IfCase;

template<typename T, int N>
struct ElseCase;

#if defined(WORKS)
    static constexpr bool
    if_then_else_return(bool b, IfCase<bool> const& ic, ElseCase<bool> const& ec, bool x);
#else
    template<typename T, typename IfFunctor, typename ElseFunctor>
    static constexpr T
    if_then_else_return(T b, IfFunctor const& ic, ElseFunctor const& ec, T x);
#endif

/****************** DEFINITIONS ******************/
template<typename T>
struct IfCase {
    constexpr T
    operator()(T t) const {
       return t;
    }
};

template<typename T, int N>
constexpr T
recursive(T t) {
   return if_then_else_return(t, IfCase<T>{}, ElseCase<T, N>{}, t);
}

template<typename T, int N>
struct ElseCase {
    constexpr T
    operator()(T t) const {
       return recursive<T, N + 1>(t);
    }
};

static constexpr int MaxRecursionDepth = 10;

template<typename T>
struct ElseCase<T, MaxRecursionDepth> {
    constexpr T
    operator()(T t) const {
       assert(false); // OK in C++14!
       return t;
    }
};

#if defined(WORKS)
    constexpr bool
    if_then_else_return(bool b, IfCase<bool> const& ic, ElseCase<bool> const& ec, bool x) {
        return b ? ic(x) : ec(x);
    }
#else
    template<typename T, typename IfFunctor, typename ElseFunctor>
    constexpr T
    if_then_else_return(T b, IfFunctor const& ic, ElseFunctor const& ec, T x) {
        return b ? ic(x) : ec(x);
    }
#endif


/****************** CALL ******************/

int main() {
    constexpr auto r = recursive(true);
}

它可以工作at CoLiRu


我最初担心如何检测实际的递归深度错误,因为我原来的部分专业化类会默默地返回错误的答案。由于您使用的是-std=c++14assertions in constexpr functions are valid,这对我来说是个新闻。我已经更新了代码以利用它。

【讨论】:

  • 好主意,谢谢!我仍在尝试了解此手动递归终止的所有含义,例如这种方法是否也适用于非平凡算法......
【解决方案2】:

通过对运行时和编译时递归使用不同的代码路径,我能够解决无休止的递归:

#include <boost/hana/integral_constant.hpp>
#include <boost/hana/unpack.hpp>
#include <boost/hana/equal.hpp>
#include <type_traits>
#include <tuple>
#include <cassert>

namespace hana = boost::hana;

namespace detail {
    /* std::forward_as_tuple(views...) is not constexpr */
    template<typename... Xs>
    static constexpr auto
    forward_as_tuple(Xs&&... xs) {
        return std::tuple<Xs...>{ 
            std::forward<Xs>(xs)... 
        };
    }
/* namespace detail */ }

template<typename Condition, typename LastStep, typename RecursionStep>
struct functor_t {
    constexpr
    functor_t(Condition const c, LastStep ls, RecursionStep rs) : c{c}, ls{ls}, rs{rs} {};

    template <typename Args>
    constexpr decltype(auto)
    eval(std::true_type, Args const& args) const {
        return hana::unpack(args, ls);
    }

    template <typename Args>
    constexpr decltype(auto)
    eval(std::false_type, Args const& args) const {
        auto vt = hana::unpack(args, rs);

        return eval( hana::unpack(vt, c), vt);
    }

    template <typename Args>
    constexpr decltype(auto)
    eval(hana::true_, Args const& args) const {
        return hana::unpack(args, ls);
    }

    template <typename Args>
    constexpr decltype(auto)
    eval(hana::false_, Args const& args) const {
        auto vt = hana::unpack(args, rs);

        return eval( hana::unpack(vt, c), vt);
    }

    template <typename Args>
    decltype(auto)
    eval(bool const& b, Args const& args) const {
        if (b) {
            return hana::unpack(args, ls);
        }

        auto vt = hana::unpack(args, rs);

        return eval(hana::unpack(vt, c), vt);
    }

    template <typename... Args>
    constexpr decltype(auto)
    operator()(Args&& ...args) const {
        return eval( c(std::forward<Args>(args)...), detail::forward_as_tuple(args...) );
    }

    Condition const c;
    LastStep ls;
    RecursionStep rs;
};

struct recurse_t {

    template <typename Condition, typename LastStep, typename RecursionStep>
    constexpr decltype(auto)
    operator()(Condition && c, LastStep && ls, RecursionStep && rs) const {
        return functor_t<Condition, LastStep, RecursionStep>{c, ls, rs};
    }

};

constexpr recurse_t recurse{};

/****************** TEST ******************/

#include <boost/hana/plus.hpp>
#include <boost/hana/minus.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/ext/std/tuple.hpp>
#include <tuple>

struct Condition {
    template<typename I, typename S, typename J>
    constexpr decltype(auto)
    operator()(I const& i, S const& s, J const& j) const{ 
        return (j == hana::int_c<1>);
    }
};

struct LastStep {
    template<typename I, typename S, typename J>
    constexpr decltype(auto)
    operator()(I const& i, S const& s, J const& j) const { 
        return hana::plus(s, i);
    }
};

struct RecursionStep {
    template<typename I, typename S, typename J>
    constexpr decltype(auto)
    operator()(I const& i, S const& s, J const& j) const { 
        return std::make_tuple(i, hana::plus(s,i), j-hana::int_c<1>);
    }
};

int main() {
    /* compute: 2*10 == 20 */
    assert(recurse(Condition{}, LastStep{}, RecursionStep{})(2,0,10) == 20);
    static_assert(recurse(Condition{}, LastStep{}, RecursionStep{})(hana::int_c<2>, hana::int_c<0>, hana::int_c<10>) == hana::int_c<20>, "");

    assert(
        recurse(
            [](auto a, auto b, auto c) { return (a == 1); },
            [](auto a, auto b, auto c) { return a+b; }, 
            [](auto a, auto b, auto c) { return std::make_tuple(a, a+b, c-1); }
        )(2,0,10) == 20
    );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    • 2016-06-16
    • 2013-04-23
    相关资源
    最近更新 更多