我正在读这个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&...);
}
main.cpp
#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 中执行与此类似的操作?
最佳答案
玩 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 和旧版本。
关于c++ - 可变函数和折叠表达式 : Fatal Error while trying to compile in Visual Studio 2017,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57343233/