【问题标题】:MSVC can't evaluate a constexpr function inside enable_ifMSVC 无法评估 enable_if 中的 constexpr 函数
【发布时间】:2018-12-16 00:14:32
【问题描述】:

考虑一个简单的实用程序函数来计算合取,并使用此实用程序来确保 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 一个神螺栓链接。所以我想知道,这是一个 MSVC 错误还是只是我遗漏了什么?

【问题讨论】:

    标签: c++ visual-c++ c++14


    【解决方案1】:

    我猜这是一个 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;
    }
    

    【讨论】:

    • 对,我使用了类似的解决方法。似乎只要使用结构而不是函数,它就可以工作。
    • 这似乎只有在基类模板参数内的函数调用中扩展参数包时才会发生。例如。以下也失败:template&lt;bool... Bools&gt; struct conjunction : std::integral_constant&lt;bool, all(Bools...)&gt; {}; 但“手动”解决方法template&lt;bool... Bools&gt; struct conjunction { static constexpr bool value = all(Bools...); }; 被接受。
    猜你喜欢
    • 1970-01-01
    • 2016-08-30
    • 2023-03-23
    • 1970-01-01
    • 2022-08-17
    • 2017-06-27
    • 2020-02-10
    • 1970-01-01
    • 2017-08-11
    相关资源
    最近更新 更多