问题描述
我已阅读有关 usage of requires
expression as a standalone feature 的这篇文章,它激励我去探索。
因此,我创建了自己的函数,无需声明概念,但使用了 requires
。
注意:我目前使用 GCC 11.1 并启用了 -std=gnu++2b
我不知道其他编译器是否可以工作,但我保证 GCC 在下面编译时没有问题:
template <typename T>
void print_if_meowable(T x) {
if constexpr (requires {
{ x.meow() } -> std::same_as<void>;
}) {
std::cout << "Meowable" << '\n';
} else {
std::cout << "Not meowable" << '\n';
}
}
// Structs
struct Dog {};
struct Cat { void meow(); };
struct Kitten : Cat {};
struct Wolf { void woof(); };
应用:
print_if_meowable(Dog{});
print_if_meowable(Cat{});
print_if_meowable(Kitten{});
print_if_meowable(Wolf{});
输出:
Not meowable
Meowable
Meowable
Not meowable
我的问题是,除了约束类型模板之外,在布尔上下文中使用 requires
表达式有多大用处? (并非用于回答基于意见的问题,而是用于 C++ 中的可能应用)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)