constexpr和lambda,是否有可能

时间:2018-03-03 15:31:44

标签: c++ constexpr

这段代码有什么问题吗?它使我的msvc崩溃在这一行。 然而,使用gcc它运作良好

constexpr auto d = for_each_tuple(t, [](auto i) {return 2.0 * i;});

但是如果我在没有constexpr的情况下使用它,我就没有问题。

以下是完整代码:

#include <iostream>
#include <string>
#include <tuple>

template<typename Function, typename ...types, std::size_t ...Is>
constexpr double for_each_impl(std::tuple<types...> t, Function f, std::index_sequence<Is...>) {
    double r{0.0};

    auto l = [&r, &f](auto t) {
        r += f(t);
    };

    (l(std::get<Is>(t)), ...);

    return r;
}

template<typename Function, typename ...types>
constexpr double for_each_tuple(std::tuple<types...> t, Function f) {
    using Indices = std::index_sequence_for<types...>;
    return for_each_impl(t, f, Indices{});
}

int main() {
    constexpr std::tuple<int, double, unsigned int> t{1, 2.0, 3u};

    constexpr auto d = for_each_tuple(t, [](auto i) {return 2.0 * i;});

    static_assert(d == 12.0, "");

    return 0;
}

0 个答案:

没有答案