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

当模板返回类型阻止实例化时,如何向用户提供漂亮的static_assert消息?

  •  0
  • NoSenseEtAl  · 技术社区  · 7 年前

    假设我想编写一个函数,返回指针非空容器的第一个元素。

    // REQUIRES: c not empty
    template<typename C>
    auto pointer_to_first(C& c) -> decltype( &(*c.begin()) ){
        return nullptr; // TODO: implement
    }
    

    如果我试着用这个 vector<bool>

    vector<bool> vb{false, false, true};
    pointer_to_first(vb);
    

    编译器给初学者带来了令人困惑的错误信息:

    错误:获取临时[-fPermission]自动的地址 指针_to_first(C&C)->decltype(&(*c.begin())){

    这是令人困惑的,因为初学者不知道代理 使用和 vb 不是暂时的。

    所以我想补充一点 static_assert 容器不能 向量(<);布尔> begin() , end() 我知道怎么做,但问题是,由于重载解析失败,用户只能看到编译器错误消息。

    有没有办法绕过这个问题?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jarod42    7 年前

    static_assert 避免使用SFINAE:

    // Your SFINAE function:
    template<typename C>
    auto pointer_to_first_impl(C& c) ->   decltype(&(*c.begin())){
      return nullptr;// TODO: implement
    }
    
    template<typename C>
    decltype(auto) pointer_to_first(C& c)
    {
        // You need to implement the traits for the check
        static_assert(my_cond<C>::value, "type is incorrect");
        return pointer_to_first_impl(c);
    }