我想声明一个依赖模板参数的成员类型:
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/