用于检查类型相等的编译时函数 [英] compile-time function for checking type equality

查看:145
本文介绍了用于检查类型相等的编译时函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现自我编译时函数检查类型相等(函数模板不带参数 bool eqTypes< T,S>())。

自我意味着不依赖于图书馆。



我不是很好。这是我试过的,但它不是我需要的。

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

这里是 live example



在C ++ 11中,如果允许使用 std :: false_type std :: 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 ,它几乎是一样的东西,可以作为标准库的一部分。


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

解决方案

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.

这篇关于用于检查类型相等的编译时函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆