在嵌套类型中保留volatile

问题描述 投票:1回答:2
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);
}

fT被推断为volatile S<int>,但n只是int。我需要做些什么来保护volatile,也就是让n成为volatile int

c++ templates
2个回答
6
投票
using n = typename std::conditional< std::is_volatile<T>::value, 
            volatile typename T::type,
            typename T::type >::type;

如果volatilen,则将T添加到volatile


3
投票

对于funsies。如果您经常需要执行此类操作,则可以将其封装在元函数中。这是中可能的实现:

#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; }; 

这是SFINAE友好的,所以如果传递的类型没有::type成员,它也不会。否则,它通过将限定符转发到它上来公开相同的类型。

Here it适用于您的示例。

© www.soinside.com 2019 - 2024. All rights reserved.