如何检查两种类型是否相同在compiletime(奖金点,如果它工作与Boost强typedef) [英] How to check if two types are same at compiletime(bonus points if it works with Boost strong typedef)
问题描述
我想知道是否可以检查2种类型在编译时是否相同。
我想出的是(idk,如果它工作,因为它感觉hackish和IDK标准,所以IDK测试时寻找)。
I was wondering if it is possible to check if 2 types are same at compile time. What I came up with is(idk if it works because it feels hackish and IDK standard that good so IDK what to look for when testing).
#include <boost/strong_typedef.hpp>
BOOST_STRONG_TYPEDEF(double, cm);
BOOST_STRONG_TYPEDEF(double, inch);
template<typename T, typename U>
static constexpr void __help()
{
}
template<typename T, typename U>
class AreSameType
{
public:
constexpr operator bool()
{
return &__help<T,U> == &__help<U,T>;
};
};
用法:
int main()
{
static_assert(AreSameType<double,float>()== false, "oh noes1");
static_assert(AreSameType<double,double>()== true, "oh noes2");
static_assert(AreSameType<int*,double*>()== false, "oh noes3");
static_assert(AreSameType<double*,double>()== false, "oh noes4");
static_assert(AreSameType<const double,double>()== false, "oh noes5");
static_assert(AreSameType<inch,cm>()== true, "oh expected"); //fires
}
所以
1)有更好的方法吗?
2)是一个函数hack保证按标准工作的地址(我不打赌:))?
1) is there a better way to it?
2) is this address of a function hack guaranteed to work by standard(I would bet not :))?
推荐答案
使用 std :: is_same
。 std :: is_same< T,U> :: value
将为真如果T和U是相同类型,否则为假。
Use std::is_same
. std::is_same<T,U>::value
will be true if T and U are the same type, false otherwise.
如果你没有C ++ 11,很容易实现
If you don't have C++11, it's easy to implement as this
template<class T, class U>
struct is_same {
enum { value = 0 };
};
template<class T>
struct is_same<T, T> {
enum { value = 1 };
};
这篇关于如何检查两种类型是否相同在compiletime(奖金点,如果它工作与Boost强typedef)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!