2011-02-23 85 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

相关问题