保持嵌套类型的挥发性

Preserve volatile in nested types

本文关键字:挥发性 嵌套类型      更新时间:2023-10-16
template<typename T>
struct S {
    using type = T;
};
volatile S<int> s;
template<typename T>
void f(T& v) {
    using n = typename T::type;
    S<n>::_; // to show
}
int main() {
     f(s);
}

f中,T推荐给volatile S<int>,但n是仅int。我该怎么做才能保留volatile,也就是说,让nvolatile int

using n = typename std::conditional< std::is_volatile<T>::value, 
            volatile typename T::type,
            typename T::type >::type;

如果Tvolatile

,将volatile添加到n

用于娱乐。如果您需要经常做这种事情,则可以将其封装在元功能中。这是C 17中的可能实现:

#include <type_traits>
template<class Trait, typename=void>
struct propogate_cv_to_type{};
template<class Trait>
struct propogate_cv_to_type<Trait, std::void_t<typename Trait::type>>
{ using type = typename Trait::type; }; 
template<class Trait>
struct propogate_cv_to_type<Trait const, std::void_t<typename Trait::type>>
{ using type = typename Trait::type const; }; 
template<class Trait>
struct propogate_cv_to_type<Trait volatile, std::void_t<typename Trait::type>>
{ using type = typename Trait::type volatile; }; 
template<class Trait>
struct propogate_cv_to_type<Trait const volatile, std::void_t<typename Trait::type>>
{ using type = typename Trait::type const volatile; }; 

它很友好,因此,如果通过的类型没有::type成员,则不会。否则,它通过将预选赛转发到它来公开相同的类型。

这里是应用于您的示例。