首先,翻转模板参数。您希望推导出 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));