2011-02-23 80 views
12

未聲明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::tuplestd::forward不是constexpr是技術原因std::tuple無法通過調用它與右值CSTR創建,但在這裏,這個問題顯然是(多)更普遍。

+1

快速提示,以'_ [A-Z]開頭的標識符是爲編譯器實現者保留的。因此,您的計劃不合格。 – 2011-02-24 07:13:15

+3

而_T是特別討厭,如果你應該移動到Windows,它是一個宏... – 2011-02-24 18:55:53

+1

@Matthieu男,@波佩爾鬆謝謝。我用T等替換了所有名稱_T,這樣其他人可以更安全/更輕鬆地嘗試代碼。 – Lars 2011-02-24 21:48:11

回答

10

一般的答案是,C++委員會的圖書館工作組沒有通過工作草案進行詳盡的拖網尋找機會使用新的核心設施。這些功能已經用於人們有時間和傾向查看可能的用途,但沒有時間進行詳盡的檢查。

有一些關於constexpr在作品中的其他用途的文章,例如November 2010 mailing中的文章。

+0

謝謝。我已經知道相關文件[N3231](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3231.html),但它沒有提到關於std的第20.3.3節::前鋒。 - 你提供的是更多的「社會理由」。我對「概念上的原因」感興趣,也就是說,在製作std :: forward constexpr方面有什麼問題,或者它會好嗎? – Lars 2011-02-23 22:54:50

+4

我看不出任何理由爲什麼不乍看。 – 2011-02-23 22:57:01

+0

有了可以在constexpr函數中傳遞和調用函數指針的問題報告(並且字面函數對象類型可以已經被constexpr了),std :: forward是非constexpr似乎是不幸的。 – 2011-02-26 06:16:33

相關問題