C ++检查语句是否可以评估为constexpr [英] C++ check if statement can be evaluated constexpr

查看:79
本文介绍了C ++检查语句是否可以评估为constexpr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以确定是否可以对constexpr求值,并将结果用作constexpr布尔值?我的简化用例如下:

Is there a method to decide whether something can be constexpr evaluated, and use the result as a constexpr boolean? My simplified use case is as follows:

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。

My target is C++2a.

我找到了以下reddit线程,但我而不是宏的忠实支持者。 https://www.reddit.com/ r / cpp / comments / 7c208c / is_constexpr_a_macro_that_check_if_an_expression /

I found the following reddit thread, but I'm not a big fan of the macros. https://www.reddit.com/r/cpp/comments/7c208c/is_constexpr_a_macro_that_check_if_an_expression/

推荐答案

这是另一种解决方案,它更通用(适用于任何表达式,而无需每次都定义单独的模板。)

Here's another solution, which is more generic (applicable to any expression, without defining a separate template each time).

此解决方案利用了(1)lambda表达式可以是从C ++ 17开始的constexpr(2)从C ++ 20开始默认可构造的lambda类型。

This solution leverages that (1) lambda expressions can be constexpr as of C++17 (2) the type of a captureless lambda is default constructible as of C++20.

这个想法是,返回 true 仅当且仅当 Lambda {}()可以出现在模板参数中时才选择,这实际上需要lambda调用

The idea is, the overload that returns true is selected when and only when Lambda{}() can appear within a template argument, which effectively requires the lambda invocation to be a constant expression.

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());
    }
}

这篇关于C ++检查语句是否可以评估为constexpr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆