为什么std :: forward丢弃constexpr-ness?

Lar*_*ars 12 c++ const move-semantics perfect-forwarding c++11

如果没有声明constexpr,std::forward将丢弃constexpr-ness以用于转发参数的任何函数.为什么std::forward不宣布constexpr自己这样可以保留constexpr-ness?

示例:(使用g ++ snapshot-2011-02-19测试)

#include <utility>

template <typename T> constexpr int f(T x) { return -13;}
template <typename T> constexpr int g(T&& x) { return f(std::forward<T>(x));}

int main() {
  constexpr int j = f(3.5f);
  // next line does not compile: 
  // error: ‘constexpr int g(T&&) [with T = float]’ is not a constexpr function
  constexpr int j2 = g(3.5f);
}
Run Code Online (Sandbox Code Playgroud)

注意:从技术上讲,很容易制作std::forwardconstexpr,例如,如此(请注意,g std::forward已被替换为fix::forward):

#include <utility>

namespace fix {
  /// constexpr variant of forward, adapted from <utility>:
  template<typename Tp>
  inline constexpr Tp&&
  forward(typename std::remove_reference<Tp>::type& t) 
  { return static_cast<Tp&&>(t); }

  template<typename Tp>
  inline constexpr Tp&&
  forward(typename std::remove_reference<Tp>::type&& t) 
  {
    static_assert(!std::is_lvalue_reference<Tp>::value, "template argument"
          " substituting Tp is an lvalue reference type");
    return static_cast<Tp&&>(t);
  }
} // namespace fix

template <typename T> constexpr int f(T x) { return -13;}
template <typename T> constexpr int g(T&& x) { return f(fix::forward<T>(x));}

int main() {
  constexpr int j = f(3.5f);
  // now compiles fine:
  constexpr int j2 = g(3.5f);
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:为什么std::forward没有定义为fix::forward

注2:这个问题与我关于constexpr std :: tuple的另一个问题有些相关,因为std::forward不是constexpr因为std::tuple不能通过调用带有rvalues的cstr来创建的技术原因,但这里的这个问题显然(更多)更通用.

Ant*_*ams 10

一般的答案是,C++委员会的图书馆工作组尚未通过工作草案进行详尽的搜索,寻找使用新核心设施的机会.这些功能已被用于人们有时间和倾向于查看可能用途的地方,但是没有时间进行详尽的检查.

有一些关于constexpr作品中其他用途的论文,例如2010年11月邮件中的那些.

  • [N3305](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3305.html)建议为`std :: forward`添加constexpr (5认同)
  • 乍一看,我看不出任何理由. (4认同)