i正在阅读此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
上应用重复的&
。
当我使用Compiler Explorer: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及以上版本。