如何使用简写语法创建一个参数化的概念?
有没有办法创建一个参数化的概念,能够与简写语法一起使用?
假设存在某个条件:
template<typename T, typename... Ps>
constexpr bool condition;
是否可以创建一个概念,使用这种语法:
template<condition_concept<p1_type, p2_type> T>
来检查 condition<T, p1_type, p2_type> 是否成立?
我本来考虑把它们包装在结构体中,但出于某种原因,它们必须在命名空间级别定义。
(顺便问一下,为什么会这样?如果有原因,可能挺有意思的。)
我知道可以使用一个 requires 子句,但在我看来,简写要更好看也更方便。
解决方案
这是一种实现方式:
#include <type_traits>
// by default, the condition is false
template <typename T, typename... Ps>
struct condition_impl : std::false_type {};
// it's always true for int and int as second parameter...
template <typename T>
struct condition_impl<T, int, int> : std::true_type {};
// except for floats
template <>
struct condition_impl<float, int, int> : std::false_type {};
// Just a helper actually, to match op requirement
template <typename T, typename... Ps>
constexpr bool condition = condition_impl<T, Ps...>::value;
// Making the bool a concept
template <typename T, typename p1, typename p2>
concept condition_concept = condition<T, p1, p2>;
// using it in order to filter input
template<typename p1, typename p2>
void foo(condition_concept<p1, p2> auto) {}
int main() {
double d{3.14};
[[maybe_unused]] float f{3.14f};
// it's not OK
// foo<int,int>(f);
// it's not OK
// foo<int,char>(d);
// it's OK
foo<int,int>(d);
}
我觉得这已经不言自明了。
我在使用偏特化来筛选条件。
condition 布尔值是对这些特化的一种辅助。
从模板布尔值获取一个概念很直接。
唯一的“转折点”是,在像 void foo(condition_concept<int, int> auto); 或 template<condition_concept<int, int> T> 这样的语法中,第一模板参数会隐式地成为应用该概念的类型。
例如,请参阅 https://cppreference.com/cpp/language/template_parameters#Type_template_parameter。
以及标准中的:https://eel.is/c++draft/temp.param#10
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。