结构成员的概念检查
检查特定结构成员是否验证给定概念的简单惯用方法是什么?
我尝试了以下方法,但不起作用,因为{ T::f }
生成类型float&
:
#include <concepts>
struct foo {
float f;
};
// ok
static_assert(std::floating_point<decltype(foo::f)>);
template<typename T>
concept has_fp_member = requires (T t) {
{ T::f } -> std::floating_point;
};
// fails
static_assert(has_fp_member<foo>);
在哪里可以删除{ T::f }
上添加的无用引用?不会让代码变得非常难看,不会添加新的概念,等等。我的主要要求是内容保持可读性!
例如
template<typename T>
concept has_fp_member = std::floating_point<decltype(T::f)>;
是非常次要的,因为我的实际概念将检查一大组属性,我不想要一堆std::foo<decltype(T::a)> && std::bar<decltype(T::b)> && ...
请注意,我使用float
作为示例,但我的问题是关于任何类型/概念的一般解决方案。
解决方案
您可能需要使用宏:
#include <concepts>
#include <type_traits>
template <class T>
std::decay_t<T> decay_copy(T&&);
#define CHECK_MEMBER(name, type)
{ decay_copy(t.name) } -> type
template<typename T>
concept has_member_variables = requires (T t) {
CHECK_MEMBER(f, std::floating_point);
CHECK_MEMBER(i, std::integral);
};
Demo.
相关文章