如何检查类型是通过 typedef 定义的还是在模板参数中使用定义的

how to check if a type is defined by typedef or using in template parameters

本文关键字:定义 参数 typedef 何检查 检查 类型      更新时间:2023-10-16

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

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。