C 检查是否可以评估语句ConstexPr
C++ check if statement can be evaluated constexpr
是否有一种方法可以决定是否可以评估某些内容,并将结果用作constexpr boolean?我简化的用例如下:
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_check_f_an_expression/
这是另一个解决方案,它更通用(适用于任何表达式,而无需每次定义单独的模板)。
此解决方案利用(1)lambda表达式可以作为C 17(2)constexpr constexpr,该类型的类型是caftureless lambda的类型,默认为C 20。
。这个想法是,仅当Lambda{}()
才能在模板参数中出现时选择返回true
的过载,这实际上要求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());
}
}
不是您所问的(我已经开发了一种自定义类型特征,特定于get_value()
静态方法...也许可以概括它知道如何),但我想您可以使用sfinae并按照以下方式做一些东西
#include <iostream>
#include <type_traits>
template <typename T>
constexpr auto icee_helper (int)
-> decltype( std::integral_constant<decltype(T::get_data()), T::get_data()>{},
std::true_type{} );
template <typename>
constexpr auto icee_helper (long)
-> std::false_type;
template <typename T>
using isConstExprEval = decltype(icee_helper<T>(0));
template <typename base>
struct derived
{
template <std::size_t I>
void do_stuff()
{ std::cout << "constexpr case (" << I << ')' << std::endl; }
void do_stuff (std::size_t i)
{ std::cout << "not constexpr case (" << i << ')' << std::endl; }
void execute ()
{
if constexpr ( isConstExprEval<base>::value )
do_stuff<base::get_data()>();
else
do_stuff(base::get_data());
}
};
struct foo
{ static constexpr std::size_t get_data () { return 1u; } };
struct bar
{ static std::size_t get_data () { return 2u; } };
int main ()
{
derived<foo>{}.execute(); // print "constexpr case (1)"
derived<bar>{}.execute(); // print "not constexpr case (2)"
}
template<auto> struct require_constant;
template<class T>
concept has_constexpr_data = requires { typename require_constant<T::get_data()>; };
这基本上是std::ranges::split_view
使用的内容。
相关文章:
- std::condition_variable::wait()如何评估给定的谓词
- 我的简单if-else语句是如何无法访问的代码
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 为什么是0;C++中的有效语句
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 如何使用"equal to"以外的评估编写开关语句
- OR 语句执行所有评估
- C 检查是否可以评估语句ConstexPr
- C :评估if语句时未识别炭值
- C++ 在 while 语句中评估基础 if 条件
- 当在if语句中时,cin如何评估为true
- 如何评估此语句
- #pragma unroll语句能否用于清理编译器预先评估的代码
- C++中分配语句的评估顺序
- 在语句中调用 std::set 函数时出现意外"if"评估结果
- C++开关语句评估