27

我想知道是否可以在编译时检查两种类型是否相同。我想出的是(idk,如果它有效,因为它感觉很hackish并且IDK标准很好,所以IDK在测试时要寻找什么)。

#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的地址是否保证按标准工作(我敢打赌不是:))?

4

1 回答 1

54

使用std::is_same. std::is_same<T,U>::value如果 T 和 U 是同一类型,则为 true,否则为 false。

如果你没有 C++11,那么很容易实现

template<class T, class U>
struct is_same {
    enum { value = 0 };
};

template<class T>
struct is_same<T, T> {
    enum { value = 1 };
};
于 2012-10-25T14:56:51.100 回答