是什么原因`std :: exchange`不是`constexpr`?

Vit*_*meo 13 c++ std constexpr c++14

std::exchange,在C++ 14中引入,规定如下:

template< class T, class U = T >
T exchange( T& obj, U&& new_value );
Run Code Online (Sandbox Code Playgroud)

替换objwith 的值new_value并返回旧值obj.

以下是cppreference的可能实现:

template<class T, class U = T>
T exchange(T& obj, U&& new_value)
{
    T old_value = std::move(obj);
    obj = std::forward<U>(new_value);
    return old_value;
}
Run Code Online (Sandbox Code Playgroud)

据我所知,没有什么可以防止std::exchange被标记为constexpr.有没有理由我错过了为什么不能constexpr,或者这只是一个疏忽?

tam*_*bre 22

截至最新的C++ 20草案,在Albuquerque ISO C++委员会会议之后,std::exchange提出constexpr了接受提案P0202R2.

  • @StoryTeller引用Herb Sutter的旅行报告:"*在这次会议上,Evolution子组还暂时允许constexpr(编译时)新的,向量和字符串*"......如果这是未来,你需要*如果您希望算法在运行时也高效,则将语义移动到constexpr函数内部 (7认同)
  • @StoryTeller为什么这么傻?没有它,在cppreference的[示例](http://en.cppreference.com/w/cpp/utility/exchange)中制作移动构造函数和赋值`constexpr`将不会[工作](https://godbolt.org /克/ JLSxWr). (6认同)
  • @Rakete1111 - 一个对象*最初*`constexpr`不会被移动(隐含的`const`会妨碍它).正如你展示Nawaz一样,在constexpr函数中使用它作为动词是一个我没有考虑的有效点(我感谢你提出它).但我仍然坚持认为它的实用性不是太大*. (3认同)
  • 这是一个愚蠢的决定IMO,尽管是无害的.但这就是答案,所以+1就是这样. (2认同)