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
303 views
in Technique[技术] by (71.8m points)

c++ - compile-time function for checking type equality

I need to implement self contained compile-time function for checking type equality (function template without arguments bool eqTypes<T,S>()).

self contained means not relying on library.

I'm not good in all this. That's what I tried, but it's not what I need.

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; 
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It's quite simple. Just define a type trait and a helper function:

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

Here is a live example.

In C++11, if you are allowed to use std::false_type and std::true_type, you would rewrite the above this way:

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

Notice, that the type trait std::is_same, which does pretty much the same thing, is available as part of the Standard Library.


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

...