gpt4 book ai didi

c++ - 如何在约束中使用 ADL?

转载 作者:行者123 更新时间:2023-12-03 06:49:40 24 4
gpt4 key购买 nike

例如,我想使用约束来确保函数 isinf为模板参数实现 T .如 Tfloat 之一, double , long double或整数类型,这可以通过以下方式完成:

#include <cmath>

template <typename T>
concept Test = requires (T a) {
std::isinf(a);
};
但是,我也想将此约束用于我自己实现的自定义非标准数据类型 isinf功能。此功能未包含在 std 中命名空间,所以我尝试了以下方法:
#include <cmath>

template <typename T>
concept Test = requires (T a) {
using std::isinf;
isinf(a);
};
这不起作用,因为 requires 子句中的每个语句都应该是有效的要求,并且 using std::isinf根本不是“要求”。
我看到了这个问题的两种解决方法:
  • 移动 using std::isinf;子句到全局命名空间。但这引入了isinf到全局命名空间,我想避免这种情况。
  • 封装using std::isinf;在名为 ABC 的命名空间中具有概念定义的子句,然后添加 using ABC::Test;直接在命名空间之后。这似乎有点奇怪。

  • 有更好的解决方案吗?

    最佳答案

    这种在 Ranges 中工作的方式是创建一个自定义点对象。这与您的第二个选项非常相似(我们在自定义命名空间中使用 using 声明),但我们还为用户提供了一种机制来调用正确的 isinf无需自己编写一堆相同类型的样板。isinf 的自定义点对象看起来像这样:

    namespace N {
    // make our own namespace
    namespace impl {
    // ... where we can bring in std::isinf
    using std::isinf;

    struct isinf_t {
    // our type is constrained on unqualified isinf working
    // in a context where std::isinf can be found
    template <typename T>
    requires requires (T t) {
    { isinf(t) } -> std::same_as<bool>;
    }
    constexpr bool operator()(T t) const {
    // ... and just invokes that (we know it's valid and bool at this point)
    return isinf(t);
    }
    };
    }

    // we provide an object such that `isinf(x)` incorporates ADL itself
    inline constexpr auto isinf = impl::isinf_t{};
    }
    现在我们有了一个对象,一个概念就直接出现了:
    template <typename T> 
    concept Test = requires (T t) {
    N::isinf(t);
    }
    这正是 range 概念被指定。

    关于c++ - 如何在约束中使用 ADL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64723265/

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