concepts return type requirement syntax two versus one template parm(概念返回类型需求语法2对1模板参数)
问题描述
我想知道std::same_as是如何定义的,以及我们如何在概念或要求中使用它。
示例:
void f1() { }
bool f2() { return true; }
template < typename T>
void Do( T func )
{
if constexpr ( requires { { func() } -> std::same_as<bool>; } )
{
std::cout << "Func returns bool " << std::endl;
}
if constexpr ( requires { { func() } -> std::same_as<void>; } )
{
std::cout << "Func returns void " << std::endl;
}
}
int main()
{
Do( f1 );
Do( f2 );
}
按预期工作。
但如果我查看std::same_as的定义,我会发现一个可能的实现:
namespace detail {
template< class T, class U >
concept SameHelper = std::is_same_v<T, U>;
}
template< class T, class U >
concept same_as = detail::SameHelper<T, U> && detail::SameHelper<U, T>;
让我纳闷的是,在这种情况下,我看到了两个模板参数T和U,而我们只需要编写一个类似{ { func() } -> std::same_as<bool>; }的参数。
在这种情况下,a{ { func() } -> std::same_as<bool>; }将转换为std::same_as<magic_return_type, bool>是某种魔法吗?
推荐答案
Aconcept一般类似于constexpr inline bool变量模板。然而,它确实有特殊的性质。关于这个问题,第一个模板参数是类型的concept是一种特殊的概念:A;类型概念。
在某些位置,可以在没有第一个模板参数的情况下使用类型概念。在这些地方,将根据第一个参数的使用方式来推断它。
在requires表达式的复合要求中,类型概念是->后面的。The first parameter of the concept will be filled in by the type of the expression E in the {}, as if by decltype((E))。
这篇关于概念返回类型需求语法2对1模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:概念返回类型需求语法2对1模板参数
基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
