一个概念需要 constexpr 值或函数吗?

Can a concept require a constexpr value or function?

本文关键字:constexpr 函数 一个      更新时间:2023-10-16

所以,我想做一些高级类型级的黑客,我真的希望能够编写一个概念,要求类型具有与之关联的constexpr int值,我稍后可以在与整数std::array模板参数相同的概念中使用它。

可以写

template<typename T>
concept bool HasCount = requires {
typename T::count;
};

但这不是我想要的;我想T::count成为一名static constexpr int. 但是,代码(甚至不包括所需的constexpr)

template<typename T>
concept bool HasCount = requires {
int T::count;
};

在 GCC 7.3.0 上不使用"错误:'int'之前的预期主表达式"进行编译。

另一个失败的尝试:可以写这个,这需要static int T::count()

template<typename T>
concept bool HasCount = requires {
{T::count()} -> int;
};

但不是这个,这就是我想要的:

template<typename T>
concept bool HasCount = requires {
{T::count()} -> constexpr int;
{T::count() constexpr} -> int; // or this
{constexpr T::count()} -> int; // or this (please forgive me for fuzzing GCC instead of reading the manual, unlike perl C++ is not an empirical science)
};

所以,我想知道是否以任何方式要求概念表达式符合 constexpr 资格,或者如果不是,是否有原因无法实现,或者它只是没有包含在规范中。

理论上,这可以通过要求T::count是有效的表达式来实现的,并要求在需要常量表达式的上下文中使用T::count是有效的。例如:

#include <type_traits>
#include <utility>
template<int> using helper = void;
template<typename T>
concept bool HasCount = requires {
// T::count must be a valid expression
T::count;
// T::count must have type int const
requires std::is_same_v<int const, decltype(T::count)>;
// T::count must be usable in a context that requires a constant expression
typename ::helper<T::count>;
};
struct S1 {
static constexpr int count = 42;
};
static_assert(HasCount<S1>);
struct S2 {
int count = 42;
};
static_assert(!HasCount<S2>);
struct S3 {
static constexpr double count = 3.14;
};
static_assert(!HasCount<S3>);

但在实践中,GCC 中概念的实现拒绝了这个程序:

<source>:20:16: error: invalid use of non-static data member 'S2::count'
static_assert(!HasCount<S2>);
^~~~~~~~~~~~
<source>:18:17: note: declared here
int count = 42;
^~
<source>:20:16: error: invalid use of non-static data member 'S2::count'
static_assert(!HasCount<S2>);
^~~~~~~~~~~~
<source>:18:17: note: declared here
int count = 42;
^~

(我认为这是一个错误。