未聲明constexpr
,std::forward
將丟棄它轉發參數的任何函數的併發性。 爲什麼std::forward
本身沒有聲明constexpr
本身,所以它可以保持constexpr?ness?爲什麼std :: forward放棄了constexpr- ness?
實施例:(帶克測試++快照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
具有被替換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
界定?
注2:這個問題在一定程度上關係到我的其他question about constexpr std::tuple爲std::forward
不是constexpr
是技術原因std::tuple
無法通過調用它與右值CSTR創建,但在這裏,這個問題顯然是(多)更普遍。
快速提示,以'_ [A-Z]開頭的標識符是爲編譯器實現者保留的。因此,您的計劃不合格。 – 2011-02-24 07:13:15
而_T是特別討厭,如果你應該移動到Windows,它是一個宏... – 2011-02-24 18:55:53
@Matthieu男,@波佩爾鬆謝謝。我用T等替換了所有名稱_T,這樣其他人可以更安全/更輕鬆地嘗試代碼。 – Lars 2011-02-24 21:48:11