使用C++模板判断是否基本类型

可以使用define来简化.

  • 方法1
template <typename T>
struct is_double
{
	operator bool()
	{
		return false;
	}
};
 
template <>
struct is_double<double>
{
	operator bool()
	{
		return true;
	}
};


//使用方法
if (!is_double<int>())
  • 方法2

#include <iostream>
#include <string>
using namespace std;

struct FalseType
{
    static bool Get()
    {
        return false;
    }
};

struct TrueType
{
    static bool Get()
    {
        return true;
    }
};

template<class T>
struct TypeTraits
{
    typedef FalseType PODTYPE;
};

template<>
struct TypeTraits<int>
{
    typedef TrueType PODTYPE;
};

template<>
struct TypeTraits<char>
{
    typedef TrueType PODTYPE;
};

template<>
struct TypeTraits<double>
{
    typedef TrueType PODTYPE;
};

template<>
struct TypeTraits<float>
{
    typedef TrueType PODTYPE;
};


//使用方法
TypeTraits<int>::PODTYPE::Get()

猜你喜欢

转载自blog.csdn.net/quantum7/article/details/88424101
今日推荐