考虑一个简单的效用函数来计算合取,并使用这个效用来确保 std::tuple
中的类型都相等。
#include <type_traits>
#include <tuple>
constexpr auto all() noexcept -> bool { return true; }
template <class... Bools>
constexpr auto all(bool const x, Bools... xs) noexcept -> bool
{
return x && all(xs...);
}
template <class T, class = void>
struct foo;
template <class T, class... Ts>
struct foo< std::tuple<T, Ts...>
, std::enable_if_t<all(std::is_same<T, Ts>::value...)>
> {
};
int main()
{
foo<std::tuple<int, int>> x;
}
GCC 和 Clang 可以处理这段代码,但 MSVC 不行。 Here's神 bolt 链接。所以我想知道,这是一个 MSVC 错误还是只是我遗漏了什么?
最佳答案
我猜这是一个 MSVC 错误。如果支持 C++17,我建议改为使用 std::conjunction .在 C++14 下,作为一种解决方法,可以从前一个链接复制“可能的实现”:
#include <type_traits>
#include <tuple>
template<class...> struct conjunction : std::true_type { };
template<class B1> struct conjunction<B1> : B1 { };
template<class B1, class... Bn>
struct conjunction<B1, Bn...>
: std::conditional_t<bool(B1::value), conjunction<Bn...>, B1> {};
template<class... B>
constexpr bool conjunction_v = conjunction<B...>::value;
template <class T, class = void>
struct foo;
template <class T, class... Ts>
struct foo< typename std::tuple<T, Ts...>
, std::enable_if_t<conjunction_v<std::is_same<T, Ts>...>>
> {
};
int main()
{
foo<std::tuple<int, int>> x;
}
关于c++ - MSVC 无法评估 enable_if 中的 constexpr 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51226444/