C 检查是否可以评估语句ConstexPr

C++ check if statement can be evaluated constexpr

本文关键字:评估 语句 ConstexPr 检查 是否      更新时间:2023-10-16

是否有一种方法可以决定是否可以评估某些内容,并将结果用作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使用的内容。