c++ - 如何为自己的类(class)专门设计标准概念?

标签 c++ c++20 c++-concepts

我有一个模板函数应适用于所有整数类型:

#include <concepts>
template<typename T>
bool odd(T n) requires std::integral<T>
{
  return n & T(1);
}

现在我想将此功能与某些用户定义的整数类型一起使用,例如boost::multiprecision::cpp_int
#include <boost/multiprecision/cpp_int.hpp>
boost::multiprecision::cpp_int n = ...
std::cout << odd(n) << std::endl;

gcc 10给
error: use of function ‘bool odd(T) requires  integral<T> [with T = boost::multiprecision ...

这是正确的。我该怎么做才能解决此问题,即如何为自己的类型专门设计标准概念?

最佳答案

how can I specialize a standard concept for my own type?



你不知道概念不能专门化。类型特征可以在某些情况下使用,但是std::integral不是您可以使用的一种,因此也不是正确的方法。

What can I do to fix this



您需要针对所使用的算法集提出正确的概念。显然,最直接的是:
template <typename T>
concept IsOddable = std::constructible_from<T, int> &&
    requires (T n) {
        { n & n } -> std::convertible_to<bool>;
    };

但是不要那样做。您可能需要某种通用的Numeric概念,并为+*%等添加要求。这些概念来自算法-因此请弄清楚算法所施加的通用要求并从那里开始工作。

关于c++ - 如何为自己的类(class)专门设计标准概念?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61642816/

相关文章:

c++ - 如何使用 alignof 强制对齐堆分配?

c++ - 使用 MSVC 的模块中的访问冲突

c++ - constexpr vector push_back 或如何 constexpr 所有的东西

c++ - 概念包含适用于函数,但不适用于结构

c++ - 他们如何在没有显式模型(又名概念图)的情况下避免基于概念的重载问题

c++ - 在 C++ 中定义 std::string 没有转义字符

c++ - 检测 parking 场线和ROI openCV

c++ - 错误 : implicitly deleted because the default definition would be ill-formed (vector of structs)

c++ - 为什么system_clock time_point不能从duration构造?

C++ 概念 : Some signatures function conversion