C++检测模板化类
C++ detect templated class
template<typename T>
struct check
{
static const bool value = false;
};
我想做的是让check<T>::value
成为真的,当且仅当T
是std::map<A,B>
或std::unordered_map<A,B>
并且A
和B
都是std::string
。所以基本上check
启用类型T
的编译时检查。我该怎么做?
当您想要允许任何比较器、哈希器、键相等比较器和分配器时,部分专用化:
template<class Comp, class Alloc>
struct check<std::map<std::string, std::string, Comp, Alloc>>{
static const bool value = true;
};
template<class Hash, class KeyEq, class Alloc>
struct check<std::unordered_map<std::string, std::string, Hash, KeyEq, Alloc>>{
static const bool value = true;
};
如果要检查T
是否使用了这些类型的默认版本(也称为仅map<A,B>
而不是map<A,B,my_comp>
,则可以省略模板参数并使用显式专用化:
template<>
struct check<std::map<std::string, std::string>>{
static const bool value = true;
};
template<>
struct check<std::unordered_map<std::string, std::string>>{
static const bool value = true;
};
如果你想一般检查它是否是任何键/值组合(和比较器/哈希器/等)的std::map
或std::unordered_map
,你可以从这里开始完全通用:
#include <type_traits>
template < template <typename...> class Template, typename T >
struct is_specialization_of : std::false_type {};
template < template <typename...> class Template, typename... Args >
struct is_specialization_of< Template, Template<Args...> > : std::true_type {};
template<class A, class B>
struct or_ : std::integral_constant<bool, A::value || B::value>{};
template<class T>
struct check
: or_<is_specialization_of<std::map, T>,
is_specialization_of<std::unordered_map, T>>{};
使用一些部分模板专用化
// no type passes the check
template< typename T >
struct check
{
static const bool value = false;
};
// unless is a map
template< typename Compare, typename Allocator >
struct check< std::map< std::string, std::string, Compare, Allocator > >
{
static const bool value = true;
};
// or an unordered map
template< typename Hash, typename KeyEqual, typename Allocator >
struct check< std::unordered_map< std::string, std::string, Hash, KeyEqual, Allocator > >
{
static const bool value = true;
};
相关文章:
- 使用CMake检测支持的C++标准
- 当套接字连接断开时检测C/C++Unix
- C/C++预处理器是否可以检测一些编译器选项
- WMI检测进程创建事件-c++
- 基于树莓pi的tensorflow lite量化ssd目标检测
- 下面是我为检测链接列表中的循环而制作的代码
- 落砂模拟碰撞检测C++和SFML
- 我可以检测和更改 gcc/g++ 中结构的当前数据对齐设置吗?
- 为什么C++编译器没有检测到正确声明的类?
- 检测win32服务创建和删除的最佳方法
- 正在LLVM中检测整数比较条件
- 如何在鼠标挂钩过程中检测拖动
- 位移操作和位掩码未检测到重复字符
- 检测 COFF 对象文件中C++内联符号
- qmake:检测目标位宽(32 位或 64 位)
- 增强精神解析器规则以检测语句中的特殊结尾
- 用于C++的静态二进制检测或二进制重写工具和框架
- Tensorflow对象检测在Python和C++(OpenCV)之间有不同的结果
- C++中的张量流对象检测
- 如何在OpenCV中检测这是谁的脸?