为什么std :: forward丢弃constexpr-ness? [英] Why does std::forward discard constexpr-ness?
问题描述
std::forward
未声明为constexpr
时,对于将参数转发到的任何函数,都将舍弃其constexpr-ness. 为什么std::forward
本身没有声明为constexpr
以便可以保持解释性?
Being not declared constexpr
, std::forward
will discard constexpr-ness for any function it forwards arguments to. Why is std::forward
not declared constexpr
itself so it can preserve constexpr-ness?
示例:(已通过g ++快照-2011-02-19测试)
Example: (tested with 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);
}
注意:从技术上讲,像这样制作std::forward
constexpr很容易(请注意,在std::forward
中g已替换为fix::forward
):
Note: technically, it would be easy to make std::forward
constexpr, e.g., like so (note that in g std::forward
has been replaced by 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);
}
我的问题是:为什么std::forward
的定义不像fix::forward
?
My question is: why is std::forward
not defined like fix::forward
?
注意2:此问题与我的其他问题有些相关关于constexpr std :: tuple 的信息,因为std::forward
不是constexpr
是std::tuple
不能通过使用rvalue调用其cstr来创建的技术原因,但是这里的问题显然(更)普遍了. /p>
Note2: this question is somewhat related to my other question about constexpr std::tuple as std::forward
not being constexpr
is the technical reason why std::tuple
cannot be created by calling its cstr with rvalues, but this question here obviously is (much) more general.
推荐答案
普遍的回答是,C ++委员会的图书馆工作组没有对工作草案进行详尽的调查,以寻找使用新核心设施的机会.这些功能已在人们有时间和意愿来考虑可能的用途的情况下使用,但是没有时间进行详尽的检查.
The general answer is that the C++ committee's Library Working Group have not done an exhaustive trawl through the working draft looking for opportunities to use the new core facilities. These features have been used where people have had the time and inclination to look at possible uses, but there is not the time for exhaustive checking.
There are some papers regarding additional uses of constexpr
in the works, such as those in the November 2010 mailing.
这篇关于为什么std :: forward丢弃constexpr-ness?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!