检查类型相等性的编译时函数

compile-time function for checking type equality

本文关键字:编译 函数 类型 检查      更新时间:2023-10-16

我需要实现用于检查类型相等的自包含编译时函数(不带参数的函数模板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_typestd::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") 
}