【问题标题】:Fold Expression: parser stackoverflow折叠表达式:解析器stackoverflow
【发布时间】:2018-05-11 21:32:06
【问题描述】:

您好,我想使用折叠表达式 , 运算符,但 MSVC 一直在用 C1026 烦我->程序太复杂了。我已将问题分解为最小示例:

#include <utility>
#include <iostream>
template<size_t idx>
void foo()
{
    //do some stuff
}
template<typename Ts>
struct ApplySomeFun;

template<size_t... Ts >
struct ApplySomeFun<std::index_sequence<Ts...>>
{

    static void execute() 
    {
        (void(foo<Ts>()), ...);// C1026
    }


};

int main()
{   
    ApplySomeFun<std::make_index_sequence<1024>>::execute();
} 

这在 gcc 中有效,但在 msvc 中无效。所以我的问题是如何在 msvc 中构建它并保持折叠表达式的清晰度。

【问题讨论】:

  • 嗯,1024 单个参数包中的元素很多。你真的需要这么长的折叠表达式吗?
  • 折叠表达式不是 100% 必要的,但它会很酷,因为它看起来很优雅并且编译速度很快(至少在 gcc 上)。
  • 你明白它不能编译只是因为它的数字太大了吗?除非您真的需要 1024 来解决实际问题,否则我不会担心。
  • 我认为HolyBlackCat 是真的:问题是1024 对于这种类型的解决方案来说太大了。开发 C++14 替代方案很容易,不是那么优雅,但并没有真正的不同。但是如果问题是1024,我想C++14解决方案也会失败。
  • 是的,需要 1024。我想我会尝试 c++14 路径。

标签: c++ templates visual-c++ variadic-templates c++17


【解决方案1】:

这是我的解决方法(感谢 max66 的提示)。

template<size_t idx>
void foo()
{
    std::cout << idx << std::endl;
}
template<typename Ts>
struct ApplySomeFun;

template<size_t... Ts >
struct ApplySomeFun<std::index_sequence<Ts...>>
{

    static void execute()
    {
        int unused[] = { 0, ((void)foo<Ts>(), 0)... };//Expander trick
        (void)unused; // blocks warnings
    }


};

int main()
{
    ApplySomeFun<std::make_index_sequence<1024>>::execute();
}

没有那么好,但它有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    相关资源
    最近更新 更多