如何确定模板专用化是否存在
How to decide if a template specialization exist
我想检查是否存在某个模板专用化,其中未定义一般情况。
鉴于:
template <typename T> struct A; // general definition not defined
template <> struct A<int> {}; // specialization defined for int
我想定义一个这样的结构:
template <typename T>
struct IsDefined
{
static const bool value = ???; // true if A<T> exist, false if it does not
};
有没有办法做到这一点(理想情况下没有C++11(?
谢谢
使用无法将sizeof
应用于不完整类型的事实:
template <class T, std::size_t = sizeof(T)>
std::true_type is_complete_impl(T *);
std::false_type is_complete_impl(...);
template <class T>
using is_complete = decltype(is_complete_impl(std::declval<T*>()));
在科里鲁现场观看
这是一个有点笨拙但有效的 C++03 解决方案:
template <class T>
char is_complete_impl(char (*)[sizeof(T)]);
template <class>
char (&is_complete_impl(...))[2];
template <class T>
struct is_complete {
enum { value = sizeof(is_complete_impl<T>(0)) == sizeof(char) };
};
在科里鲁现场观看
这是一个替代实现,始终使用@Quentin使用的相同技巧
C++11版本
template<class First, std::size_t>
using first_t = First;
template<class T>
struct is_complete_type: std::false_type {};
template<class T>
struct is_complete_type<first_t<T, sizeof(T)>> : std::true_type {};
魔杖盒示例
暂定C++03版本不起作用
template<typename First, std::size_t>
struct first { typedef First type; };
template<typename T>
struct is_complete_type { static const bool value = false; };
template<typename T>
struct is_complete_type< typename first<T, sizeof(T)>::type > { static const bool value = true; };
在这种情况下,错误是
prog.cc:11:8: 错误:模板参数在部分专用化中不可推导: struct is_complete_type
{ static const bool value = true; }; ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ prog.cc:11:8: 注意:"T">
相关文章:
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 如何检查QList中是否存在值
- 根据某个函数是否存在启用模板
- 地图计数确实很重要,或者只是检查是否存在
- C++中是否存在 std::conditional 的懒惰等价物?
- 无论如何,我可以确定构造函数是否存在吗?
- COM :是否可以查看是否存在对我的某个 COM 对象的进程外引用?我可以释放它吗?
- 堆分配的对象是否存在永不为空的唯一所有者?
- 扩展类中的可选 vir 函数,测试它在运行时是否存在
- 模板化检查是否存在带有参数列表的类成员函数?
- 是否存在包含负号的isdigit函数(过载)
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 检查编译时是否存在静态函数
- 向量是否存在行主要形式?
- 检查 TinyXML 中的元素是否存在
- 检测是否存在具有 C++17 的类成员
- 虚拟继承中是否存在多重继承?
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符
- std::weak_ptr 和相应的 std::shared_ptr 之间是否存在数据竞争?
- 是否存在用于 C 或 C++ 中常见数学运算(例如最小值、最大值和平均值)的可导入库?