简体   繁体   English

C ++ 20 constexpr std ::运行时的复制优化

[英]C++20 constexpr std::copy optimizations for run-time

cppreference.com says: cppreference.com说:

In practice, implementations of std::copy avoid multiple assignments and use bulk copy functions such as std::memmove if the value type is TriviallyCopyable 实际上,如果值类型为TriviallyCopyable,则std :: copy的实现会避免多个赋值并使用批量复制函数,例如std :: memmove

However, the page also states that the overloads which don't take an execution policy will be constexpr since C++20. 但是,该页面还指出,自C ++ 20以来,不执行执行策略的重载将是constexpr Will the standard forbid these run-time optimizations (since std::memmove is not constexpr) or is there a way to optimize constexpr functions for run-time? 标准是否会禁止这些运行时优化(因为std::memmove不是constexpr)或有没有办法优化constexpr函数的运行时?

We can have our cake and eat it to, too. 我们也可以吃蛋糕,也可以吃。

Let's just consider the simplest specialization of copy , the one that copies char s. 我们只考虑copy的最简单的专业化,即复制char的。 In C++17, that might look like: 在C ++ 17中,这可能看起来像:

char* copy(char const* first, char const* last, char* d)
{
    memcpy(d, first, last - first);
    return d + (last - first);
}

Of course, we can't just slap constexpr on that because memcpy isn't a constexpr function, that won't work. 当然,我们不能只拍constexpr上,由于memcpy是不是一个constexpr功能,这是行不通的。 But it only doesn't work during constant evaluation. 但它只是在不断评估期间不起作用。 What we need is a way to conditionally use memcpy if we're at runtime. 我们需要的是一种在运行时有条件地使用memcpy的方法。

We have such a thing in C++20, std::is_constant_evaluated() : 我们在C ++ 20中有这样的东西, std::is_constant_evaluated()

constexpr char* copy(char const* first, char const* last, char* d)
{
    if (std::is_constant_evaluated()) {
        while (first != last) {
            *d++ = *first++;
        }
        return d;       
    } else {
        memcpy(d, first, last - first);
        return d + (last - first);
    }
}

And now we have an algorithm that does the efficient thing at runtime but still works during constexpr evaluation time. 现在我们有一个算法可以在运行时执行高效的操作,但在constexpr评估时仍然有效。


Note: It is if (std::is_constant_evaluated()) , never if constexpr (std::is_constant_evaluated()) . 注:这是if (std::is_constant_evaluated()) 从来没有 if constexpr (std::is_constant_evaluated()) The later is equivalent to if constexpr (true) { ... } . 后者等同于if constexpr (true) { ... } gcc 10.1 will start warning on this erroneous usage. gcc 10.1将在此错误用法时开始警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM