c++ - 如何检查类型是否由 typedef 定义或在模板参数中使用

标签 c++ templates c++11 template-meta-programming

我想声明一个依赖模板参数的成员类型:

template< typename T >
struct bc_allocator_traits
{
public:
    using this_type = bc_allocator_traits;
    using allocator_type = T;
    using value_type = typename allocator_type::value_type;
    using pointer_type = typename allocator_type::pointer_type; 
...

在此示例中,pointer_type 取决于模板参数(allocator_type)。但是为模板参数定义 pointer_type 是可选的,如果模板参数不存在这种类型,我想使用默认类型,如 value_type*

有什么方法可以在我的类中实现这个可选的成员类型定义吗?

最佳答案

这就像是 void_t 的后代。

template<class ...>
using void_t = void;

// workaround for some compilers: 
// template<class...> struct voider { using type = void; }; 
// template<class... Args> using void_t = typename voider<Args...>::type;

template<class T, class = void>
struct pointer_type_or_default { 
    using type = typename T::value_type*;
};

template<class T>
struct pointer_type_or_default<T, void_t<typename T::pointer_type>> { 
    using type = typename T::pointer_type;
};

然后

using pointer_type = typename pointer_type_or_default<allocator_type>::type;

想法是部分特化是可行的,并且仅当 T::pointer_type 有效且表示类型时才使用。

对于未执行 CWG 1558 决议的编译器,需要解决方法.这包括高达 4.9.2 的 GCC(当前主干版本正确编译别名模板版本,参见 PR 63825),显然还有 MSVC。

关于c++ - 如何检查类型是否由 typedef 定义或在模板参数中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27566894/

相关文章:

c++ - 如何找到任何对象使用的内存

c++ - Qt dragEnterEvent 未被调用

c++ - 当它是左值时如何存储引用,当它是右值时如何存储拷贝

c++ - std::move into static_pointer_cast:为什么 static_pointer_cast 没有右值引用重载?

c++ - array<int,2> dim 在这段代码中是什么意思?

c++ - 为什么编译器需要 `delete [] p` 而不是 `delete p[]` ?

c++ - 如何在 mongocxx find_one_and_update 的文档中设置值

javascript - mapbox 由于模板未初始化

c++ - 如何使基类模板函数对派生类实例可见,而无需转换或复制签名?

c++ - 在 C++11 中创建一个保留锁定尝试顺序的锁