6

the intention of the following c++ code is to wrap the ternary operator (?:) in a separate function, which later on will help with building a syntax tree.

Before looking at real c++ snippet let's take a quick look at what it does in pseudo code:

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

Unfortunatly Clang has problems with terminating the recursion when the ternary operator (?:) is wrapped within a template function:

/****************** 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);
}

Build results:

GCC (4.9.2) compiles both variants without an error, but Clang (3.5 to 3.8) fails with the following error message:

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.

But why? How can this code be rewritten so that Clang does not complain anymore?

Thank you very much in advance.

EDIT 1:

  • I've shorted the compiler message, hopefully increasing its readability. For a full backtrace, please take a look at those Coliru links provided above.

  • Removing the constexpr specifier will work around this Clang error. But this also reduces functionality and thus is not an option.

Jakob
  • 83
  • 9
  • 1
    Please find code & build results for GCC at Coliru [here (reg. function)](http://coliru.stacked-crooked.com/a/817e88c473b1a02e) and [here (tmpl. function)](http://coliru.stacked-crooked.com/a/af8253f0627e1543). – Jakob Jun 20 '16 at 20:33
  • Please use a [MCVE] example, stray away. In this question's case, if you reduce the problem to *one* error from *one* function which produces the error, it will be easier to help you. – NonCreature0714 Jun 20 '16 at 20:39
  • Thank you for your hint! If I remove `constexpr` the problem is gone, but this will also reduce functionality. If I remove `#ifdef` etc. IMHO it is harder to see what I mean with _reg. function_ and _tmpl. function_, but I can remove those if helpful. Without the split between declarations and definitions I had compilation errors with GCC. What exactly did you have in mind here? – Jakob Jun 20 '16 at 20:57
  • You don't need to show all the error messages. If one of the declarations/definitions causes the error, simply use that as an example, instead of all of them. Of course, don't change the functionality/purpose of your code or use poor programming practices; that isn't what I'm suggesting. Try compiling with the least amount of code which causes the error with the best representation of your problem. – NonCreature0714 Jun 20 '16 at 21:03
  • It may be that the code you use is the least required, but some of the errors are exact duplicates. – NonCreature0714 Jun 20 '16 at 21:07
  • I assume that removing some `constexpr` specifiers is not an option? This is needed for a compile-time computation? – rhashimoto Jun 21 '16 at 01:45
  • @NonCreature0714: Ah, I see. Those duplicates are gone :-) – Jakob Jun 21 '16 at 08:45
  • @rhashimoto: You are right, removing `constexpr` is not an option :-/ I've added a remark to the question. – Jakob Jun 21 '16 at 08:48

2 Answers2

0

One workaround is to limit recursion yourself by adding a counter to the template arguments of the constructs participating in recursion, updating the counter on the recursive call, and using partial specialization to terminate recursion.

I made these changes to your program:

  • Changed IfCase and ElseCase (IfCase only for symmetry) to template classes instead of regular classes with a template member function. This allows partial specialization.

  • Added an integer counter template argument to ElseCase and recursive().

  • Incremented the counter when calling recursive() in ElseCase.

  • Created a partial specialization of ElseCase at an arbitrary recursion depth that does not make a recursive call. The maximum depth should be tuned to avoid the clang++ limit.

Here's the code:

#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);
}

It works at CoLiRu.


I was initially worried about how to detect an actual recursion depth error, as my original partially specialized class would silently return the wrong answer. Since you are using -std=c++14, assertions in constexpr functions are valid, which was news to me. I have updated the code to make use of this.

Community
  • 1
  • 1
rhashimoto
  • 15,650
  • 2
  • 52
  • 80
  • Nice idea, thanks! I am still trying to understand all implications of this manual recursion termination, e.g. whether this approach is applicable to non-trivial algorithms, too... – Jakob Jun 22 '16 at 11:00
0

By using different code paths for runtime and compile time recursion I was able to work around endless recursion:

#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
    );
}
Jakob
  • 83
  • 9