【发布时间】:2020-02-24 13:19:05
【问题描述】:
我目前正在试验新的 c++2a 'concepts' 功能。我下面代码的目标是检查模板结构的某些属性。作为第一个模板参数is 'reserved' for the type to be checked,我很难使用没有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?
}
【问题讨论】:
标签: c++ c++20 c++-concepts