gpt4 book ai didi

c++ - 非类型模板参数和要求

转载 作者:行者123 更新时间:2023-12-03 06:50:08 25 4
gpt4 key购买 nike

我正在学习概念,所以我想不出一种方法来限制非类型模板参数的值(非类型)。
Example可以编译的代码,尽管我希望它没有(由于失败的要求):

#include <cassert>

enum Bla{
Lol,
Haha
};

template<Bla b>
requires requires{
// my guess is that this just checks that this is valid expression, not
// that it is true
b>1;
}
void f(){
assert(b>1);
}

int main() {
f<Lol>(); // compiles, not funny ;)
}
笔记:
这是简化的示例(我想“模板重载”),所以 static_assert对我不好,并且由于语法很丑陋,我试图避免 std::enable_if

最佳答案

如果您只有 bool 条件而没有其他条件,请执行以下操作:

template<Bla b>
requires(b > 1)
void f() {}
如果需要在同一 requires -expression中检查更多内容,则可以使用其他更长的语法:
template<Bla b>
requires requires
{
requires b > 1;
// ^~~~~~~~
}
void f() {}

关于c++ - 非类型模板参数和要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64858240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com