먼저 템플릿 매개 변수를 뒤집습니다. 당신이 기본적으로 원하는 것은 조건부 식을 캐스팅하는 것입니다
template <typename TypeToReturnAs, typename AlignedStorageType>
decltype(auto) forward_as_another_type(AlignedStorageType&& storage) {
return *reinterpret_cast<TypeToReturnAs*>(&storage);
}
다음 : 당신은 AlignedStorageType
추론 할 다른 하나는 명시 적으로 지정해야합니다. AlignedStorageType&&
이 X&&
인 경우 TypeToReturnAs&&
으로 전송하고 싶습니다. X&
인 경우 TypeToReturnAs&
으로 표시됩니다. X const&
인 경우 TypeToReturnAs const&
으로 지정합니다. 당신이 할 수있는, 당신은 단지 일회성으로 이것을 사용하는 경우, 또는
template <typename TypeToReturnAs, typename AlignedStorageType>
decltype(auto) forward_as_another_type(AlignedStorageType&& storage) {
using R = match_reference_t<AlignedStorageType&&, TypeToReturnAs>;
return static_cast<R>(*reinterpret_cast<TypeToReturnAs*>(&storage));
}
: 다음
template <class T, class U> struct match_reference;
template <class T, class U> struct match_reference<T&, U> { using type = U&; };
template <class T, class U> struct match_reference<T const&, U> { using type = U const&; };
template <class T, class U> struct match_reference<T&&, U> { using type = U&&; };
template <class T, class U> using match_reference_t = typename match_reference<T,U>::type;
그리고 :
우리는 기준에 맞게 유형의 특성을 추가 할 수 있습니다 단지 조건부로 그 로직을 작성 :
template <typename TypeToReturnAs, typename AlignedStorageType>
decltype(auto) forward_as_another_type(AlignedStorageType&& storage) {
using R = std::conditional_t<
std::is_lvalue_reference<AlignedStorageType>::value,
TypeToReturnAs&,
TypeToReturnAs&&>;
return static_cast<R>(*reinterpret_cast<TypeToReturnAs*>(&storage));
}
나 :
using R = std::conditional_t<
std::is_lvalue_reference<AlignedStorageType>::value,
TypeToReturnAs&,
TypeToReturnAs>;
return std::forward<R>(*reinterpret_cast<TypeToReturnAs*>(&storage));
std :: move에서와 같이'typename remove_reference :: type &&'의 반환 값이 도움이 될까요? –