1

我简化了产生错误的代码,发现即使是这个简单的计数函数也会给我一个错误(见下文):

#include <boost/hana/tuple.hpp>
#include <boost/hana/fold.hpp>
#include <boost/hana/plus.hpp>
#include <boost/hana/integral_constant.hpp>

int main() {
    using namespace boost;

    constexpr auto inc = [](auto n, auto el) { return hana::int_c<n> + hana::int_c<1>; };
    constexpr auto count = hana::fold(hana::make_tuple(hana::int_c<3>),
                                      hana::int_<0>{},
                                      inc
    );

    return 0;

}

错误(省略了一些看似无关的):

 /usr/local/include/boost/hana/detail/variadic/foldl1.hpp:202:57: error: ‘static constexpr decltype(auto) boost::hana::detail::variadic::foldl1_impl<2u>::apply(F&&, X1&&, X2&&) [with F = const main()::<lambda(auto:1, auto:2)>&; X1 = boost::hana::integral_constant<int, 0>; X2 = boost::hana::integral_constant<int, 3>]’ called in a constant expression
             return foldl1_impl<sizeof...(xn) + 1>::apply(
                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
                 static_cast<F&&>(f), static_cast<X1&&>(x1), static_cast<Xn&&>(xn)...
                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
             );
             ~                                            
In file included from /usr/local/include/boost/hana/fold_left.hpp:18:0,
                 from /usr/local/include/boost/hana/concept/foldable.hpp:19,
                 from /usr/local/include/boost/hana/core/to.hpp:16,
                 from /usr/local/include/boost/hana/bool.hpp:17,
                 from /usr/local/include/boost/hana/tuple.hpp:16,
                 from ...:
/usr/local/include/boost/hana/detail/variadic/foldl1.hpp:31:41: note: ‘static constexpr decltype(auto) boost::hana::detail::variadic::foldl1_impl<2u>::apply(F&&, X1&&, X2&&) [with F = const main()::<lambda(auto:1, auto:2)>&; X1 = boost::hana::integral_constant<int, 0>; X2 = boost::hana::integral_constant<int, 3>]’ is not usable as a constexpr function because:
         static constexpr decltype(auto) apply(F&& f, X1&& x1, X2&& x2) {
                                         ^~~~~
/usr/local/include/boost/hana/detail/variadic/foldl1.hpp:32:39: error: call to non-constexpr function ‘main()::<lambda(auto:1, auto:2)> [with auto:1 = boost::hana::integral_constant<int, 0>; auto:2 = boost::hana::integral_constant<int, 3>]’
             return static_cast<F&&>(f)(static_cast<X1&&>(x1),
                    ~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
                                        static_cast<X2&&>(x2));

我在 g++ 6.3 中使用了 c++17。看起来它说 lambda 不被视为 constexpr,但在我看来它只使用常量值。任何人都可以向我建议如何使此代码正常工作吗?(它的目的是计算传递给折叠的元组中的元素数量)

4

1 回答 1

0

如果您的编译器不支持 constexpr lambda,您必须自己写出闭包类型(在命名空间或类范围内,而不是在函数范围内,因为本地类不能有成员模板):

constexpr struct inc_t {
    template<class N, class T>
    constexpr auto operator()(N n, T) const { return hana::int_c<n> + hana::int_c<1>; }
} inc;

否则,您仍然可以使用 hana,但类型系统将无法使用计算结果。

于 2017-06-23T12:55:17.117 回答