首页 > 解决方案 > 可变参数函数和折叠表达式:尝试在 Visual Studio 2017 中编译时出现致命错误

问题描述

我正在阅读此Q/A,其中一些答案提供了在 C++17 中使用折叠表达式的可能解决方案。我想我会在自己的代码中尝试这种技术。

这是我尝试过的:

一些标题

#pragma once

#include <bitset>
#include <type_traits>

using Bit = std::bitset<1>;

template<typename... Bits>
typename std::enable_if<(std::is_same<Bits, Bit>::value && ...), Bit>::type
And(Bits... bits) {
    return (bits&...);
}

主文件

#include <iostream>
#include "Some Header"

int main()
{   
    Bit b1_0{0};
    Bit b1_1{1};
    Bit b2_0{0};
    Bit b2_1{1};

    // Intended uses:
    Bit res1 = And(b1_0, b1_1, b2_0); // res1 should = 0
    Bit res2 = And(b1_1, b2_1); // res2 should = 1

    std::cout << "res1 = " << res1.to_string() << '\n';
    std::cout << "res2 = " << res2.to_string() << '\n';

    return 0;
}

我正在使用 Visual Studio 2017;这无法编译我得到一个"fatal error C1001".

我不知道它是否来自折叠表达式,或者我是否尝试将重复&应用于每个Bit传递给函数等的重复。

当我使用编译器资源管理器尝试此操作时:goldbot它使用 GCC 或 Clang 编译良好,但在 Visual Studio 中失败...

我如何能够在 Visual Studio 中执行与此类似的操作?

标签: c++visual-studio-2017c++17variadic-templatesfold-expression

解决方案


玩 goldbot 似乎您的代码从 MSVC v19.21 开始编译。

我不明白以前有什么问题;无论如何,通过constexpr如下函数

template <typename ... Bits>
constexpr bool all_bits ()
{ return (std::is_same_v<Bits, Bit> && ...);  }

template<typename... Bits>
std::enable_if_t<all_bits<Bits...>(), Bit>
 And(Bits... bits) {
    return (bits & ...);
}

似乎也适用于 v19.20 和旧版本。


推荐阅读