c++ - enable_if_t 中包含折叠表达式的编译器错误

标签 c++ templates c++17 enable-if fold-expression

我有以下代码,我在其中使用折叠表达式来评估所有包参数是否都可以转换为第一个函数参数。出于某种原因,当我进行看似非常微不足道的更改时,它无法在 msvc 上编译:

#include <type_traits>

#define TRY 1

#if TRY == 1

template<typename B, typename... Args,
std::enable_if_t<((std::is_convertible_v<Args&, B&> && ...)), bool> = true>
void fn(B b, Args...args) {}

#else

template<typename B, typename... Args,
typename = std::enable_if_t<(std::is_convertible_v<Args&, B&> && ...)>>
void fn(B b, Args...args) {}

#endif

int main()
{
    fn(5, 4, 2);
    return 0;
}

TRY 更改为 0 以使其编译,演示地址:https://godbolt.org/z/EGvQ-N

我遗漏的两个变体之间是否存在重要区别,或者这是编译器错误?

最佳答案

冒着稍微偏离主题的风险,我不确定折叠表达式是这里的最佳选择。我鼓励您使用 MSVS 支持的 std::conjunction 变体:

- std::enable_if_t<((std::is_convertible_v<Args&, B&> && ...)), bool> = true>
+ std::enable_if_t<std::conjunction_v<std::is_convertible<Args&, B&>...>, bool> = true>

没错,它更冗长,但也许更清晰。我遵从@NathanOliver 按照最初的要求追踪潜在的 MSVS 错误。

(本来会把它作为注释,但认为代码块更清晰。)

关于c++ - enable_if_t 中包含折叠表达式的编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56978499/

相关文章:

c++ - 使用参数包和元组创建一个简单的表达式类

c++ - 嵌套名称说明符中使用的不完整类型,为什么?

C++ 在静态方法中使用枚举

c++ - std::function 复制构造函数是否要求模板类型参数类型是完整类型?

c++ - visual c++ 复制文本框内容

wpf - 关于正确重新模板化 DataGrid

C++/Eigen : Get type of matrix argument to a template written for MatrixBase

c++ - 明确的 range-v3 decltype 评估为无效?

c++ - 获取C++类成员变量全名

c++ - 这是什么意思?