Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

c++ - How to check if two types are same at compiletime(bonus points if it works with Boost strong typedef)

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>;
    };
};

usage :

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
}

So

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 :))?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use std::is_same. std::is_same<T,U>::value will be true if T and U are the same type, false otherwise.

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 };
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...