有没有一种方法可以决定是否可以对某些内容进行 constexpr 求值,并将结果用作 constexpr 布尔值?我的简化用例如下:
template <typename base>
class derived
{
template<size_t size>
void do_stuff() { (...) }
void do_stuff(size_t size) { (...) }
public:
void execute()
{
if constexpr(is_constexpr(base::get_data())
{
do_stuff<base::get_data()>();
}
else
{
do_stuff(base::get_data());
}
}
}
我的目标是C++2a。
我发现了以下 reddit 线程,但我不太喜欢宏。https://www.reddit.com/r/cpp/comments/7c208c/is_constexpr_a_macro_that_check_if_an_expression/ https://www.reddit.com/r/cpp/comments/7c208c/is_constexpr_a_macro_that_check_if_an_expression/
这是另一个更通用的解决方案(适用于任何表达式,无需每次定义单独的模板)。
该解决方案利用了 (1) 从 C++17 开始,lambda 表达式可以是 constexpr (2) 从 C++20 开始,无捕获 lambda 的类型是默认可构造的。
这个想法是,返回的重载true
当且仅当Lambda{}()
可以出现在模板参数中,这实际上要求 lambda 调用是常量表达式。
template<class Lambda, int=(Lambda{}(), 0)>
constexpr bool is_constexpr(Lambda) { return true; }
constexpr bool is_constexpr(...) { return false; }
template <typename base>
class derived
{
// ...
void execute()
{
if constexpr(is_constexpr([]{ base::get_data(); }))
do_stuff<base::get_data()>();
else
do_stuff(base::get_data());
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)