我有一个模板函数应适用于所有整数类型:
#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/