선언되지 않았다면 constexpr
, std::forward
은 인수를 전달하는 모든 함수에 대해 constexpr-ness를 무시합니다. 왜 std::forward
은 constexpr
으로 선언되지 않으므로 constexpr-ness를 유지할 수 있습니까?std :: forward가 constexpr-ness를 버리는 이유는 무엇입니까?
예 : (g 테스트 ++ 스냅 샷 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);
}
참고 : 기술적으로, 그렇게 (즉, g에 std::forward
이 가지고주의처럼, 예를 들어 std::forward
constexpr을 쉽게 만들 수있을 것입니다) 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 :이 질문은 다소하지 constexpr
되는 것은 std::tuple
이 우변과의 CSTR를 호출하여 생성 할 수없는 이유를 기술적 인 이유입니다 내 다른 question about constexpr std::tuplestd::forward
으로 관련이있다, 그러나 여기이 질문에 분명히 (훨씬) 더 일반적이다.
[_ [A-Z]'로 시작하는 식별자는 컴파일러 구현 자에게 예약됩니다. 귀하의 프로그램은 부적절한 형태입니다. –
_T는 매크로가있는 Windows로 옮겨야하는 경우에 특히 불쾌합니다. –
@Matthieu M, @Bo Persson Thanks. 다른 사람들이 코드를보다 안전하고 쉽게 시도 할 수 있도록 T라는 이름으로 _T를 대체했습니다. – Lars