C++概念:如何使用'concept'检查模板化结构的属性?
C++ Concepts: How to use 'concept' to check the property of a templated struct?
我目前正在试验新的c++2a"概念"功能。我下面代码的目标是检查模板结构的某些属性。由于第一个模板参数是为要检查的类型"保留"的,因此在没有requires
表达式或手动指定模板参数的情况下,我很难使用该概念。这不是什么大不了的事,但我喜欢concept
表示法,因为它很清晰。有办法解决这个问题吗?
编译器
gcc-g++-10.0 (GCC) 10.0.1 20200119 (experimental)
Copyright (C) 2020 Free Software Foundation, Inc.
编译命令
g++-10.0 -std=c++2a file.cc
代码
#include <concepts>
/// Struct has template arguments and a property that can be checked in a concept.
template <bool a> struct A {
constexpr static bool property() noexcept { return a; }
};
template <typename T, bool a> concept hasProp = std::is_same_v<T, A<a>> && A<a>::property();
template <bool a> requires hasProp<A<a>, a> void works(A<a> c) {}
template <bool a, hasProp<a> c> void deductionError(c d) {};
// This is a sketch of what I'd like to do:
// template <A<a, b> Class, bool a, bool b> concept hasProp = Class::property;
int main() {
A<true> a;
A<false> b;
works(a);
//works(b); //doesn't compile as the constraint is not fulfilled, which is desired.
//deductionError(a); // I get why this deduction error occurs, but is it possible to do this
// in a clean way using concepts without having so specify template arguments?
}
救援的部分类模板专业化:
template<class T>
struct HasProp : std::false_type{};
template<bool a>
struct HasProp<A<a>> : std::integral_constant<bool, A<a>::property()>
{};
template <class T>
concept hasProp = HasProp<T>::value;
template <bool a>
requires hasProp<A<a>>
void works(A<a>) {}
template<hasProp C>
void deductionError(C){} // no longer a deductionError
Demo
这确实(也许不必要(将您的概念直接与A
联系起来。
你可以这样做(就像@Barry回答的那样(:
template <class T>
concept hasProp = T::property();
Demo2
您真的需要连接到A
吗?
template <typename T> concept hasProp = T::property();
template <bool a> requires hasProp<A<a>> void works(A<a>); // ok
template <hasProp C> void deductionError(C); // also ok
如果你确实需要搭配,你可以将其完全本地添加到hasProp
:
// unfortunately this is hard to generalize due to the non-type template parameter
template <typename T> struct is_A : std::false_type { };
template <bool b> struct is_A<A<b>> : std::true_type { };
template <typename T> concept hasProp = is_A<T>::value && T::property();
// ... and the rest works as before
template <bool a> requires hasProp<A<a>> void works(A<a>); // ok
template <hasProp C> void deductionError(C); // also ok
无论哪种方式,hasProp
都应该只采用一种类型。
相关文章:
- C++概念:如何使用'concept'检查模板化结构的属性?
- "perf_event_attr"结构的"read_format"属性的选项到底是什么?
- 使用内存地址访问结构的属性值
- 通过指针算法调用结构的结构属性
- 无法在 unordered_set 中找到 () 结构属性
- 嵌套结构属性继承
- 在C++中循环数组时访问结构属性
- 为什么结构属性声明和初始化顺序的行为是这样的?
- gcc 显示结构属性为 0,但 clang 显示不同的值
- 使用 Spirit 将 std::vector<std::vector<double> 解析为结构属性
- 如何使用索引访问C 结构属性值
- 从外部函数访问外部结构属性
- 如何在C++中将结构属性转换为指针引用
- 如何通过字符串名称访问结构属性
- 提升灵气自定义句法属性(通过语义动作设置结构属性的特定成员)
- boost::spirit::qi具有相同的简单自适应结构属性的规则会导致编译错误
- 结构属性操作符重载
- 读取int*类型的结构属性值时遇到问题
- 模板递归中的函数、结构枚举和结构属性有什么区别?
- 在 C 中,除了使用 val 之外,不能更改结构属性 #define