代码之家  ›  专栏  ›  技术社区  ›  DarthRubik

使用“hana::is\ u valid”失败,并带有常量引用

  •  2
  • DarthRubik  · 技术社区  · 6 年前

    我正在使用hana来确定对象是否具有 Length 诸如此类的成员:

    using boost::hana::is_valid;
    
    
    static const auto has_length
        = is_valid([](const auto& obj)
                -> decltype(obj.Length(),void()) {});
    

    这工作很好…我可以做静态资产与它整天我的心内容。所以下一步是合乎逻辑地 enable_if 函数:

    template<typename T>
    auto foo(T t) -> std::enable_if_t<has_length(t), void>
    {
    }
    struct mine
    {
        int Length() const { return 0; }
    };
    
    int main()
    {
        foo(mine{});
    }
    

    这很管用…但是一旦我换了衣服 T const T& godbolt

    所以我的问题是:为什么会这样?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Jason Rice    6 年前

    问题是调用引用不是constexpr的函数不是constexpr。这就是 hana::is_valid integral_constant -类似于包含静态constexpr布尔值的值,因此我们可以只查看返回类型。看到了吗 bool_

    举个例子:

    #include <boost/hana.hpp>
    #include <type_traits>
    
    namespace hana = boost::hana;
    
    static auto has_length = hana::is_valid([](auto&& t)
      -> decltype(t.Length()) { });
    
    template <typename T>
    auto foo(T const& t)
      -> std::enable_if_t<decltype(has_length(t)){}, void>
                       // ^-- notice the return type 
                       // is a boolean integral constant
    { }
    
    struct mine
    {
      int Length() const { return 0; }
    };
    
    int main()
    {
      foo(mine{});
    }