检查类型相等性的编译时函数
compile-time function for checking type equality
我需要实现用于检查类型相等的自包含编译时函数(不带参数的函数模板bool eqTypes<T,S>()
)。
self - contained表示不依赖库。
我不擅长这一切。那是我尝试过的,但那不是我需要的。
template<typename T>
bool eq_types(T const&, T const&) {
return true;
}
template<typename T, typename U>
bool eq_types(T const&, U const&) {
return false;
}
这很简单。只需定义一个类型trait和一个辅助函数:
template<typename T, typename U>
struct is_same
{
static const bool value = false;
};
template<typename T>
struct is_same<T, T>
{
static const bool value = true;
};
template<typename T, typename U>
bool eqTypes() { return is_same<T, U>::value; }
下面是一个的实例。
在c++ 11中,如果允许使用std::false_type
和std::true_type
,可以这样重写上面的代码:
#include <type_traits>
template<typename T, typename U>
struct is_same : std::false_type { };
template<typename T>
struct is_same<T, T> : std::true_type { };
template<typename T, typename U>
constexpr bool eqTypes() { return is_same<T, U>::value; }
注意,类型trait std::is_same
,它做了几乎相同的事情,可以作为标准库的一部分使用。
下面是您如何在C中做到这一点,而不需要任何神奇的GCC扩展:
#define CHECKED_TYPE(original_type, p) ((conversion_type*) (1 ? p : (original_type*) 0))
E。g:
void *q = CHECKED_TYPE(int, &y);
如果y
不是int
,将触发编译错误。
#define CHECK_TYPE_EQUAL(type_a, type_b) {
type_a type_a##_var __attribute__((unused));
type_b *type_b##_ptr __attribute__((unused));
_Pragma("GCC diagnostic push")
_Pragma("GCC diagnostic error "-Wincompatible-pointer-types"")
type_b##_ptr = &type_a##_var;
_Pragma("GCC diagnostic pop")
}
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 是什么原因导致它无法编译?它是声明签名还是在函数本身的实现中
- C++:编译时检查匹配的函数调用对?
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- C++ 在编译时具有函数计算全局变量
- 在运行时解析函数,而不是在编译C++解析函数
- C++中的双边友语函数:如何使其编译?
- 编译 CUDA 与数学函数的叮当
- CPU_ONLY构建:编译函数 Forward() 会给出错误"undefined reference..."
- 使用额外的模板参数编译函数
- 编译函数时遇到问题
- 注释函数的内容,但保持对函数的调用不变.编译器是否弄清楚不编译函数
- 如何根据模板中的类型编译函数
- XPATHNavigator的编译函数中的"后代"是什么意思?
- 如何为编译时已知的参数的多个值编译函数
- 编译函数模板时出现"expected nested-name-specifier"错误
- 无法编译C++函数
- 防止基于模板参数编译函数(或部分函数)
- 用C++编译函数模板时出错