保持嵌套类型的挥发性
Preserve volatile in nested types
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
,也就是说,让n
为volatile int
?
using n = typename std::conditional< std::is_volatile<T>::value,
volatile typename T::type,
typename T::type >::type;
如果T
是volatile
。
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
成员,则不会。否则,它通过将预选赛转发到它来公开相同的类型。
这里是应用于您的示例。
相关文章:
- CRTP:为什么获得嵌套类型和派生类的嵌套方法有区别
- 为什么在VS2015中模板相关的嵌套类型名称中不需要typename关键字?
- 为什么嵌套类型的基类不需要"typename"?
- 如何在C++中的另一个模板函数中使用属于模板化类的嵌套类型?
- 保持嵌套类型的挥发性
- 具有嵌套类型的类的概念
- 将嵌套类型的类分开为标题和源
- 如何解决C++嵌套类型的循环依赖关系
- 在 C++11 中,从私有嵌套类型继承是否合法?
- C++ 递归嵌套类型和名称注入
- 如何定义一个模板类函数,该函数在类外的签名中具有嵌套类型的模板参数
- 访问模板参数T的嵌套类型,即使T是指针
- 为什么reverse_iterator双重定义其嵌套类型
- 嵌套类型:结构与类
- 如何对嵌套类型执行部分模板专用化
- 如何解析可选的嵌套类型,如 std::allocator_traits
- 模板和嵌套类型查找
- 在 c++ 中显示嵌套类型定义的最基本类型声明
- 无法推断出嵌套类型的模板函数
- C++使用别名访问嵌套类型(使用 vs typedef)