如何测试 member 在概念上是否完整?
How to test if member is integral in concept?
我试图定义一个概念来测试特定成员变量(在示例中,'x')是否存在并且是整数类型。不过,我感到很困惑,因为 v.x
returns 和 int&
因此 std::integral
检查失败。我怎样才能使这项工作?
#include <concepts>
template <typename T>
concept isIntegralX = requires(T v) {
{v.x} -> std::integral;
};
template <typename T>
requires isIntegralX<T>
void bar(const T& base)
{
}
class Foo
{
public:
int x{0};
void baz()
{
bar<Foo>(*this);
}
};
int main()
{
return 0;
}
错误:
note: the expression 'is_integral_v<_Tp> [with _Tp = int&]' evaluated to 'false'
您可以将概念更改为:
template <typename T>
concept isIntegralX = std::is_integral_v<decltype(T::x)>;
decltype(T::x)
在此处产生确切的类型 int
。
对于多个成员,您可以
template <typename T>
concept isIntegralXandY = std::is_integral_v<decltype(T::x)> && std::is_integral_v<decltype(T::y)>;
I'm getting stumped though, since v.x returns an int& and thus the std::integral check fails. How can I make this work?
您可以尝试进行显式转换以将左值表达式转换为右值:
template <typename T>
concept isIntegralX = requires(T v) {
{ decltype(v.x)(v.x) } -> std::integral;
// Or you could write: `{ static_cast<decltype(v.x)>(v.x) } -> std::integral;`
// ...
};
// ...
回复 OP 在 . See here for details about std::conjunction. In general, you would want to check <type_traits> 下针对 C++ 提供的与类型相关的元编程实用程序作为评论发布的进一步问题。
template <typename T>
concept is_x_and_y_integral = std::conjunction_v<
std::is_integral<decltype(T::x)>,
std::is_integral<decltype(T::y)>
>;
我试图定义一个概念来测试特定成员变量(在示例中,'x')是否存在并且是整数类型。不过,我感到很困惑,因为 v.x
returns 和 int&
因此 std::integral
检查失败。我怎样才能使这项工作?
#include <concepts>
template <typename T>
concept isIntegralX = requires(T v) {
{v.x} -> std::integral;
};
template <typename T>
requires isIntegralX<T>
void bar(const T& base)
{
}
class Foo
{
public:
int x{0};
void baz()
{
bar<Foo>(*this);
}
};
int main()
{
return 0;
}
错误:
note: the expression 'is_integral_v<_Tp> [with _Tp = int&]' evaluated to 'false'
您可以将概念更改为:
template <typename T>
concept isIntegralX = std::is_integral_v<decltype(T::x)>;
decltype(T::x)
在此处产生确切的类型 int
。
对于多个成员,您可以
template <typename T>
concept isIntegralXandY = std::is_integral_v<decltype(T::x)> && std::is_integral_v<decltype(T::y)>;
I'm getting stumped though, since v.x returns an int& and thus the std::integral check fails. How can I make this work?
您可以尝试进行显式转换以将左值表达式转换为右值:
template <typename T>
concept isIntegralX = requires(T v) {
{ decltype(v.x)(v.x) } -> std::integral;
// Or you could write: `{ static_cast<decltype(v.x)>(v.x) } -> std::integral;`
// ...
};
// ...
回复 OP 在
template <typename T>
concept is_x_and_y_integral = std::conjunction_v<
std::is_integral<decltype(T::x)>,
std::is_integral<decltype(T::y)>
>;