gpt4 book ai didi

c++ - 为什么这个enable_if函数模板不能专用于VS2017?

转载 作者:可可西里 更新时间:2023-11-01 18:29:05 25 4
gpt4 key购买 nike

以下使用 VS2015 编译,但在 VS2017 中失败并出现以下错误。代码是否在做一些非标准的事情,已在 VS2017 中修复,或者 VS2017 应该编译它?

#include "stdafx.h"
#include <type_traits>

template <typename E>
constexpr auto ToUnderlying(E e)
{
return static_cast<std::underlying_type_t<E>>(e);
}

template<typename T>
bool constexpr IsFlags(T) { return false; }

template<typename E>
std::enable_if_t<IsFlags(E{}), std::underlying_type_t<E>> operator | (E lhs, E rhs)
{
return ToUnderlying(lhs) | ToUnderlying(rhs);
}

enum class PlantFlags { green = 1, edible = 2, aromatic = 4, frostTolerant = 8, thirsty = 16, growsInSand = 32 };

bool constexpr IsFlags(PlantFlags) { return true; }

int main()
{
auto ored = PlantFlags::green | PlantFlags::frostTolerant;

return 0;
}

错误是:

c:\main.cpp(24): error C2893: Failed to specialize function template 'enable_if<false,_Ty>::type
operator |(E,E)'
with
[
_Ty=underlying_type<_Ty>::type
]
c:\main.cpp(24): note: With the following template arguments:
c:\main.cpp(24): note: 'E=PlantFlags'
c:\main.cpp(24): error C2676: binary '|': 'PlantFlags' does not define this operator or a conversion to a type acceptable to the predefined operator

最佳答案

这绝对是 Visual Studio 中的错误。它compiles on GCC and Clang .它似乎与评估为模板参数的 constexpr 函数有关。作为临时解决方法,您可以制作一个模板变量:

template <typename T>
bool constexpr is_flags_v = IsFlags(T{});

template<typename E>
std::enable_if_t<is_flags_v<E>, std::underlying_type_t<E>> operator | (E lhs, E rhs)
{
return ToUnderlying(lhs) | ToUnderlying(rhs);
}

On Godbolt

关于c++ - 为什么这个enable_if函数模板不能专用于VS2017?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46104002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com