首先翻转模板参数。你想AlignedStorageType
来推断,另一个被明确指定:
template <typename TypeToReturnAs, typename AlignedStorageType>
decltype(auto) forward_as_another_type(AlignedStorageType&& storage) {
return *reinterpret_cast<TypeToReturnAs*>(&storage);
}
接下来,你基本上要的是有条件投的表达。如果AlignedStorageType&&
是X&&
,则要将其转换为TypeToReturnAs&&
。如果是X&
,则为TypeToReturnAs&
。如果是X const&
,则为TypeToReturnAs const&
。
我们可以添加型性状只是匹配参考:
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 = match_reference_t<AlignedStorageType&&, TypeToReturnAs>;
return static_cast<R>(*reinterpret_cast<TypeToReturnAs*>(&storage));
}
或者,如果你只使用这是一个一次性的,你可以只写逻辑作为条件:
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));
返回值'typename remove_reference :: type &&'在std :: move帮助? –