一个概念需要 constexpr 值或函数吗?
Can a concept require a constexpr value or function?
所以,我想做一些高级类型级的黑客,我真的希望能够编写一个概念,要求类型具有与之关联的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;
^~
(我认为这是一个错误。
相关文章:
- 条件constexpr函数
- constexpr 函数中的非文字(通过 std::is_constant_evaluated)
- constexpr 函数获取常量字符*
- 如何在 constexpr 函数中实现回退运行时
- 在非 constexpr 函数中作为左值传递的变量上使用 'constexpr' 函数
- NVCC 错误:string_view.h:constexpr 函数返回是非常量
- constexpr函数中的静态constexpr变量
- 在 constexpr 函数中断言
- G++ 编译器是否在未使用返回值的情况下将 constexpr 函数视为常规函数?
- constexpr 函数的常量引用参数:gcc/msvc vs clang/icc
- constexpr 函数在编译时获取值,即使我的变量不是 constexpr
- 如何正确地对 constexpr 函数进行单元测试
- 为什么 std::launder 是一个 constexpr 函数?
- 我可以使用 constexpr 函数声明一个静态数组吗?
- 用于连接向量的 Constexpr 函数
- 在非constexpr函数上添加的constexpr限定符不会触发任何警告
- 为什么 std::get<T> 其中 T 是调用 constexpr 函数失败的结果?
- 在constexpr函数中插入许多模板
- 在enable_if_t中调用 constexpr 函数
- constexpr 函数中的 for 循环无法使用 MSVC 19.23 进行编译